【问题标题】:How to rename uploaded file in Flask Web Framework如何在 Flask Web 框架中重命名上传的文件
【发布时间】:2014-03-14 15:38:02
【问题描述】:

我有如下蓝图,并使用flask-upload上传文件

@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)

我改变 照片 = form.photo_upload.data 到 照片 = form.photo_upload.data.lower() 但它不起作用 如何重命名上传的文件名?

【问题讨论】:

    标签: file file-upload upload flask


    【解决方案1】:

    http://pythonhosted.org/Flask-Uploads/中有您的问题的答案

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

    参数:
    storage – 要保存的上传文件。
    文件夹 – 上传集中要保存到的子文件夹。
    name - 保存文件的名称。如果它以点结尾,则文件的扩展名将附加到末尾。

    例如:user_photos.save(pathToDirectory, name=NewName)

    【讨论】:

    • 我不确定这是否有效。我得到TypeError: save() got an unexpected keyword argument 'name'
    【解决方案2】:

    我使用以下方法动态重命名上传的文件

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

    【讨论】:

    • 简单准确
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多