Flask-Uploads always throwing 'UploadNotAllowed' error even with no constraints

3.3k Views Asked by At

Flask-uploads has something called UploadSet which is described as a "single collection of files". I can use this upload set to save my file to a predefined location. I've defined my setup:

app = Flask(__name__)
app.config['UPLOADS_DEFAULT_DEST'] = os.path.realpath('.') + '/uploads'
app.config['UPLOADED_PHOTOS_ALLOW'] = set(['png', 'jpg', 'jpeg'])
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

# setup flask-uploads
photos = UploadSet('photos')
configure_uploads(app, photos)

@app.route('/doit', method=["POST"])
def doit():
    myfile = request.files['file']
    photos.save(myfile, 'subfolder_test', 'filename_test')

    return ''' blah '''

This should save to ./uploads/photos/subfolder_test/filename_test.png

My test image is: 2.6MB and is a png file. When I upload this file, I get the error:

...
File "/home/btw/flask/app.py", line 57, in doit
    photos.save(myfile, 'subfolder_test', 'filename_test')
File "/usr/local/lib/python2.7/dist-packages/flaskext/uploads.py", line 388, in save
    raise UploadNotAllowed()
UploadNotAllowed

However it doesn't say exactly what is not allowed. I have also tried removing all constraints, but the app still throws this error. Why?

EDIT:

Okay, so I figured out that it's not actually the constraints that is causing the problem. It is the subfolder and/or the filename that is causing the problem:

# This works
# saves to: ./uploads/photos/filename_test.png
photos.save(myfile)

But I want to save to my custom location ./uploads/photos/<custom_subdir>/<custom_filename>. What is the correct way of doing this?

2

There are 2 best solutions below

0
On BEST ANSWER

You need to give your filename_test the extension as well

photos.save(myfile, 'subfolder_test', 'filename_test.png')

The UploadSet checks the extension on the new file name and will throw the exception if the new extension is not allowed.

Since you are not giving the new file an extension, it does not recognize it.

0
On

You can add a dot to file's name, then the file's extension will be appended.

photos.save(myfile, 'subfolder_test', 'filename_test' + '.')

save(storage, folder=None, name=None)
Parameters:
storage – The uploaded file to save.
folder – The subfolder within the upload set to save to.
name – The name to save the file as. If it ends with a dot, the file’s extension will be appended to the end.