简体   繁体   English

如何读取上传的文件数据而不将其保存在 Flask 中?

[英]How to read uploaded file data without saving it in Flask?

First uploading a file using html form.首先使用html表单上传文件。 I don't want to store that file in the project directory.我不想将该文件存储在项目目录中。 Without saving how can I read all the file contents?不保存如何读取所有文件内容?

If you want only to read data from file then simply use .read()如果您只想从文件中读取数据,那么只需使用.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如果您想将它与需要文件名的函数一起使用,那么通常它也可以与file-like对象一起使用,您可以直接使用它

ie. 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. 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.您还可以使用io.BytesIO()在内存中创建file-like对象。

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}">'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM