Skip to main content
 首页 » 编程设计

python之如何限制用户可以上传到我的表单的文件类型

2025年02月15日14del

我有一个包含文件上传字段的表单,我还制作了一个包含已批准文件类型列表的变量。我还将上传路由到某个文件夹中如何使用以下变量...

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) 

要使其只能使用这些文件类型?

请您参考如下方法:

这是一个使用当前函数的非常简单的示例,您可以使用 File Upload Patten 中的示例对此进行改进,但这最低限度地显示了如何检查提交的扩展名是否在您的 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)