1

您好,
我正在尝试在上传具有不允许的文件类型的文件或在未选择任何文件的情况下提交时处理错误。
我得到的只是“flask_uploads.exceptions.UploadNotAllowed”和网页“内部服务器错误”。我想闪烁一条错误消息,但不知道如何处理该错误。我用谷歌搜索并阅读了文档,但找不到方法。
选择和提交正确类型的文件/文件(在本例中为 IMAGES)时,一切正常。
谢谢!

if request.method == 'POST':
        if form.validate_on_submit() and 'artwork' in request.files:

            art = form.artwork.data


            this_artf = art_f+'/'+str(order_no_art)

            app.config['UPLOADED_IMAGES_DEST'] = this_artf
            images = UploadSet('images', IMAGES)
            configure_uploads(app, images)

            for image in art:
                images.save(image)
4

2 回答 2

1

在实例上调用方法时处理flask_uploads.exceptions.UploadNotAllowed异常。saveUploadSet

from flask_uploads.exceptions import UploadNotAllowed
from flask import flash # make sure to configure secret key for your app
#....

error_files = []
for image in art:
    try:
        images.save(image)
    except flask_uploads.exceptions.UploadNotAllowed as err:
        error_files.append(image.filename)
        continue

flash(error_files, 'error')

然后,您可以通过获取闪烁的消息来呈现呈现模板中的文件。

于 2021-05-07T07:22:22.120 回答
1

正如您所说,您已经查看了文档...

我刚刚增强了https://github.com/jugmac00/flask-reuploaded中显示的示例,处理了提到的UploadNotAllowed异常。

一定不要忘记先导入异常!

...
from flask_uploads.exceptions import UploadNotAllowed
...

@app.route("/", methods=['GET', 'POST'])
def upload():
    if request.method == 'POST' and 'photo' in request.files:
        try:
            photos.save(request.files['photo'])
            flash("Photo saved successfully.")
            return render_template('upload.html')
        except UploadNotAllowed:
            flash("File type not allowed!")
            return render_template('upload.html')
    return render_template('upload.html')

这是一个通用的答案,但我很肯定您可以将其应用于您的案例。

顺便说一句,我看到您在请求处理中配置了应用程序:

if request.method == 'POST':
    if form.validate_on_submit() and 'artwork' in request.files:
        art = form.artwork.data
        this_artf = art_f+'/'+str(order_no_art)
        app.config['UPLOADED_IMAGES_DEST'] = this_artf
        images = UploadSet('images', IMAGES)
        configure_uploads(app, images)

虽然这目前有效,但这不是它应该做的方式。

就是关于这几行...

app.config['UPLOADED_IMAGES_DEST'] = this_artf
images = UploadSet('images', IMAGES)
configure_uploads(app, images)

您必须将这些行移到请求上下文之外,例如在模块顶部或在应用程序工厂中。

免责声明:我是Flask-Reuploaded.

于 2021-05-07T07:35:41.300 回答