I'm trying to upload a file with Flask and write a renamed file at completion. Per the Flask-Uploads docs, save() has a name parameter for this purpose. I receive TypeError: save() got an unexpected keyword argument 'name' when using the code below. If I omit the name portion of the save function, file.save(os.path.join('/path/to/uploads', filename)), everything works as intended.
My intent is to prepend the cust value from the wtform that the filefield is located at as the filename that is written, custvalue_filename.extension, as evidenced by my attempt with name=renfn.
views.py
def fc_upload():
form = InvFcUploadForm(next=request.args.get('next'))
if request.method == 'POST' and form.validate_on_submit():
file = request.files['file']
if file:
filename = secure_filename(file.filename)
renfn = str(form.cust.data) + '_' + filename + '.'
file.save(os.path.join('/path/to/uploads',
filename), name=renfn)
flash('File uploaded.', 'success')
return render_template('inventory/fc_upload.html', form=form)
I'm just learning python and Flask, so I fully suspect I'm missing something obvious. Thank you in advance.
Per Flask's API documentation, the content of the
files
attribute of therequest
object is aMultiDict
object whose values hold aFileStorage
object. As you can see from the Werkzeug documentation linked below, thesave()
method of these objects do not accept aname
keyword parameter.http://werkzeug.pocoo.org/docs/0.9/datastructures/#werkzeug.datastructures.FileStorage
I haven't tested it myself, but to do what you want in this case you may want to try modifying the
filename
attribute of theFileStorage
object. Alternately, open a file object manually with the name mangled in the fashion you wish and pass it in as the first parameter to thesave()
method (just remember to callclose()
on the file object afterwards if you do so).