File Is Empty After Saving Flask Uploads
I've been trying to upload a file using Flask and HTML forms. Now I can save an uploaded file but it shows up empty (0 bytes). After that I store the form entries in a database. So
Solution 1:
We don't really know what the class photos
is, nor what it's method save
does, but that's where the error is probably occurring.
Try this instead:
request.files['photo'].save('test.jpg')
Solution 2:
I realized that flask has a habit of including one empty file upload with the exact same name and details as one of the file attachments(usually the first attachment) WHEN you use the 'multiple' attribute in your form.
My workaround was to
- create a temporary random filename and save the file upload
- use os.stat(temp_filename).st_size to check if the file is empty
- if the file is empty, delete it with os.remove, otherwise, rename the file to your preferred [secure] filename
an example...
# ...defupload_file(req):
if req.method != 'POST': return# file with 'multiple' attribute is 'uploads'
files = req.files.getlist("uploads")
# get other single file attachmentsif req.files:
for f in req.files: files.append(req.files[f])
for f in files:
ifnot f.filename: continue
tmp_fname = YOUR_TEMPORARY_FILENAME
while os.path.isfile(tmp_fname):
# you can never rule out the possibility of similar random # names
tmp_fname = NEW_TEMPORARY_FILENAME
# TEMP_FPATH is he root temporary directory
f.save(os.path.join(TEMP_FPATH, tmp_fname))
# and here comes the trickif os.stat(os.path.join(TEMP_FPATH, tmp_fname)).st_size:
os.system("mv \"{}\" \"{}\" > /dev/null 2> /dev/null".format(
os.path.join(TEMP_FPATH, tmp_fname),
os.path.join(ACTUAL_FILEPATH, f.filename))
))
else:
# cleanup
os.remove(os.path.join(TEMP_FPATH, tmp_fname))
pass@app.route("/upload", methods=["POST"])defupload():
upload_files(request)
return"files are uploaded!"# ...
Post a Comment for "File Is Empty After Saving Flask Uploads"