user1288188
user1288188

Reputation: 67

How to rename uploaded file in Flask Web Framework

i have blueprint like below, and using flask-upload for uploading file

@blueprint.route('/', methods=['GET', 'POST'])
def upload_file1():
    # user = User.query.filter_by(id=current_user.id).first_or_404()
    form = PhotoFormUpload()
    if request.method == 'POST':
        file = request.files['file']
            if file and allowed_file(file.filename):
                foto = form.photo_upload.data.lower()
                filename = user_photos.save(foto)
                update_avatar = User.query.filter_by(id=current_user.id).update(dict(avatar=filename))
                db.session.commit()
                flash('Upload Success', category='success')
                return render_template('upload/display_photo.html', filename=filename)
          else:
              return render_template('upload/upload.html', form=form)

i change foto = form.photo_upload.data to foto = form.photo_upload.data.lower() but it doesnt works how do i rename uploaded file name?

Upvotes: 6

Views: 11908

Answers (2)

fcennecf
fcennecf

Reputation: 213

Answer on your question exist in http://pythonhosted.org/Flask-Uploads/

save(storage, folder=None, name=None)

Parameters:
storage – The uploaded file to save.
folder – The subfolder within the upload set to save to.
name – The name to save the file as. If it ends with a dot, the file’s extension will be appended to the end.

Example: user_photos.save(pathToDirectory, name=NewName)

Upvotes: 10

Jibin Mathew
Jibin Mathew

Reputation: 5102

I used the following method to rename the uploaded file on the fly

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

Upvotes: 4

Related Questions