Home > Software engineering >  How to read uploaded file data without saving it in Flask?
How to read uploaded file data without saving it in Flask?

Time:06-15

First uploading a file using html form. I don't want to store that file in the project directory. Without saving how can I read all the file contents?

CodePudding user response:

If you want only to read data from file then simply use .read()

uploaded_file = request.files.get('uploaded_file')

data = uploaded_file.read()

print(data)

And if you want to use it with function which needs filename then usually it may work also with file-like object and you can use it directly

ie. Pillo.Image

from PIL import Image

uploaded_file = request.files.get('uploaded_file')

img = Image.open(uploaded_file)
img.save('new_name.jpg')

ie. pandas.DataFrame

import pandas as pd

uploaded_file = request.files.get('uploaded_file')

df = pd.read_csv(uploaded_file)

You can also use io.BytesIO() to create file-like object in memory.

from PIL import Image
import io

uploaded_file = request.files.get('uploaded_file')

data = uploaded_file.read()

file_object = io.BytesIO(data)
#file_object.seek(0)

img = Image.open(file_object)
img.save('new_name.jpg')
import pandas as pd
import io

uploaded_file = request.files.get('uploaded_file')

data = uploaded_file.read()

file_object = io.BytesIO(data)
#file_object.seek(0)

df = pd.read_csv(file_object)

But this is more useful when you want to save/generate data without writing on disk and later send it back to browser.

uploaded_file = request.files.get('uploaded_file')

img = Image.open(uploaded_file)

# generate smaller version
img.thumbnail((200,200))

# write in file-like object as JPG
file_object = io.BytesIO()
img.save(file_object, 'JPEG')

# get data from file
data = file_object.getvalue()  # get data directly
# OR
#file_object.seek(0)           # move to the beginning of file after previous writing/reading
#data = file_object.read()     # read like from normal file

# send to browser as HTML
data = base64.b64encode(data).decode()
html = f'<img src="data:image/jpg;base64, {data}">'
  • Related