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
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
an example...
# ...
def upload_file(req):
if req.method != 'POST': return
# file with 'multiple' attribute is 'uploads'
files = req.files.getlist("uploads")
# get other single file attachments
if req.files:
for f in req.files: files.append(req.files[f])
for f in files:
if not 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 trick
if 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"])
def upload():
upload_files(request)
return "files are uploaded!"
# ...