Reputation:
I have a form which has a file upload field,I have also made a variable which contains a list of approved file types. I have also routed the uploads to go into a certain folder how do I use the following variable...
FILE_TYPES = set(['txt', 'doc', 'docx', 'odt', 'pdf', 'rtf', 'text', 'wks', 'wps', 'wpd'])
To incorporate into my function...
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)
To make it so only these file types can be used?
Upvotes: 3
Views: 1887
Reputation: 5362
Here is a really simple example using your current function, you can improve upon this using examples from the File Upload Patten, but this minimally shows how to check if the submitted extension is in your FILE_TYPES
set:
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)
Upvotes: 1