首先使用html表单上传文件。我不想将该文件存储在项目目录中。没有保存,我怎么能读取所有的文件内容?
如果您只想从文件中读取数据,那么只需使用.read()
uploaded_file = request.files.get('uploaded_file')
data = uploaded_file.read()
print(data)
如果你想和需要文件名的函数一起使用通常它也可以和file-like
对象一起使用你可以直接使用
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)
您也可以使用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)
但是当你想保存/生成数据而不写入磁盘并稍后将其发送回浏览器时,这更有用。
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}">'