I'm using Flask for uploading files. In order to prevent storing same file twice, I'm intending to calculate md5 from the file content, and store the file as . unless the file is already there.
@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
file = request.files['file']
#next line causes exception
img_key = hashlib.md5(file).hexdigest()
Unfortunatelly, hashlib.md5 throws the exception:
TypeError: must be string or buffer, not FileStorage
I've already tried file.stream - same effect.
Is there any way to get md5 from the file without saving it temporarily?
Python for web development using Flask Handling file upload in Flask is very easy. It needs an HTML form with its enctype attribute set to 'multipart/form-data', posting the file to a URL. The URL handler fetches file from request. files[] object and saves it to the desired location.
Werkzeug provides some subclasses of common Python objects to extend them with additional features. Some of them are used to make them immutable, others are used to change some semantics to better work with HTTP.
request.files['file']
is of type FileStorage
which has a read()
method.
Try doing:
file = request.files['file']
#file.read() is the same as file.stream.read()
img_key = hashlib.md5(file.read()).hexdigest()
More info on FileStorage
: http://werkzeug.pocoo.org/docs/datastructures/#werkzeug.datastructures.FileStorage
From the Flask docs
files
A MultiDict with files uploaded as part of a POST or PUT request. Each file is stored as FileStorage object. It basically behaves like a standard file object you know from Python, with the difference that it also has a save() function that can store the file on the filesystem.
If it's the same as a file object you should be able to do this
img_key = hashlib.md5(file.read()).hexdigest()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With