我有一个包含文件上传字段的表单,我还创建了一个包含已批准文件类型列表的变量。我还将上传内容路由到某个文件夹,如何使用以下变量...
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)
为了使它只能使用这些文件类型?
答案 0 :(得分:1)
以下是使用当前函数的一个非常简单的示例,您可以使用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)