Question

If user doesn't select a file in form (equals PHP UPLOAD_ERR_NO_FILE ), request.files['file'] also return a FileStorage object, I am using request.files['file'].filename == '' to check, any better way ? I have seen Flask Doc but can't find the answer.

'file' in request.files will not work on user doesn't select file, browser also will submit a 0 length and filename equals '' (empty string) part.

and how do I detect uploaded file was only partially uploaded error (equals PHP UPLOAD_ERR_PARTIAL) ?

Was it helpful?

Solution

Now I am using

if request.files['file'].filename == '':
    return 'No selected file'

or using file length check

import os

file = request.files['file']
file.seek(0, os.SEEK_END)
if file.tell() == 0:
    return 'No selected file'

OTHER TIPS

Try:

if not request.files.get('file', None):
    pass

If you want have most control over the files, you can use http://pythonhosted.org/Flask-Uploads/

import imghdr

def validate_image(stream):
    header = stream.read(512)
    stream.seek(0)
    format = imghdr.what(None, header)
    if not format:
        return None
    return '.'+format

class UploadFiles(Resource):
   def post(self):
      doc=request.files.get('image')
      if  validate_image(doc.stream):
         print('file validated')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top