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

 ̄綄美尐妖づ 提交于 2021-01-28 00:32:18

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/31884903/flask-uploads-always-throwing-uploadnotallowed-error-even-with-no-constraints

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!