Flask Uploads - TypeError: save() got an unexpected keyword argument 'name'

2.6k Views Asked by At

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.

2

There are 2 best solutions below

0
On

Per Flask's API documentation, the content of the files attribute of the request object is a MultiDict object whose values hold a FileStorage object. As you can see from the Werkzeug documentation linked below, the save() method of these objects do not accept a name 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 the FileStorage 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 the save() method (just remember to call close() on the file object afterwards if you do so).

0
On

I was facing the same issue and I resolved it by using something like

file = request.files['file']
file.filename = "abc.txt"  #some custom file name that you want
file.save("Uploads/"+file.filename)