如何限制用户在表单中上传的文件类型?

3

我有一个表单,其中有一个文件上传字段,我还创建了一个变量,其中包含一组已批准的文件类型。我还将上传路由到特定文件夹中,如何使用以下变量...

FILE_TYPES = set(['txt', 'doc', 'docx', 'odt', 'pdf', 'rtf', 'text', 'wks', 'wps', 'wpd'])

为了将其整合到我的函数中...

if form.validate_on_submit():
    flash('Form successfully submitted')
    print "Form successfully submitted"
    filename = secure_filename(form.file_upload.data.filename)
    form.file_upload.data.save('uploads/' + filename)
    return redirect('home')
else:
    filename = None
    print(form.errors)  
    return render_template('index.html',
                            title='Application Form',
                            form=form,
                            filename=filename)

使得只有这些文件类型可以被使用?

我尝试着按照这个指南操作,但是我很难理解如何将它集成到我的函数中。 - user7209225
1个回答

1
这是一个非常简单的示例,使用您当前的函数,您可以使用文件上传模式中的示例进行改进,但最基本的是演示如何检查提交的扩展名是否在您的FILE_TYPES集合中:
if form.validate_on_submit():
    flash('Form successfully submitted')
    print "Form successfully submitted"
    submit_name = form.file_upload.data.filename
    if '.' in submit_name and submit_name.rsplit('.', 1)[1] in FILE_TYPES:
        filename = secure_filename(submit_name)
        form.file_upload.data.save('uploads/' + filename)
        return redirect('home')
    else:
        flash('File (%s) is not an accepted format' % submit_name)
        print submit_name
else:
    flash('form failed validation')
filename = None
print(form.errors)  
return render_template('index.html',
                        title='Application Form',
                        form=form,
                        filename=filename)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接