For example, in the official documentation Uploading Files — Flask Documentation, how to save the file uploaded by the save ()
method on the server Although it has been introduced, I could not find a way to read it as it is without saving the file, so I will leave it as a memorandum.
In Flask request.files.get ()
(or request.files.getlist () [i] You can run
) to get the Werkzeug datastructures.FileStorage
object. The stream
of this object is the stream body of the uploaded file. Furthermore, FileStorage.stream
seems to inherit ʻio.BufferedIOBase`, so this stream should be boiled. It seems that you should just bake it.
If you want to read the uploaded file as text, it is convenient to make it a text stream with ʻio.TextIOWrapper`. ..
Here is a sample that reads a CSV file uploaded from a client.
import io
from flask import Flask, jsonify, request
@app.route('/upload/', methods=['POST'])
def csv_upload():
filebuf = request.files.get('csvfile')
if filebuf is None:
return jsonify(message='Please specify the file'), 400
elif 'text/csv' != filebuf.mimetype:
return jsonify(message='Only CSV files will be accepted'), 415
text_stream = io.TextIOWrapper(filebuf.stream, encoding='cp932')
for row in csv.reader(text_stream):
# do something
return jsonify(message=f'{filebuf.filename!r}Loaded'), 200
Recommended Posts