如何在Flask中上传文件时更改文件更改名称?

时间:2020-02-17 20:52:36

标签: python html flask file-upload jinja2

我正在尝试为我的团队创建一个Web应用程序,我们希望它可以拍摄用户上传的照片并在上传时对其进行重命名。现在,我在机器上的目录中有文件可以进入。我的应用程序需要3个输入:名称,电子邮件和要上传的文件。当用户单击“上传”按钮时,我希望文件以他们输入的电子邮件地址显示在我的目录中。例如:

Name: trent
Email: trent@trent.com
File: photo_of_trent.jpg

我希望上传的文件显示在我的目录中,即trent@trent.com.jpg。

我的Python / Flask代码如下:

import os
from flask import Flask, render_template
from flask_uploads import UploadSet, configure_uploads, IMAGES, patch_request_class
from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileRequired, FileAllowed
from wtforms import StringField
from wtforms import SubmitField
from wtforms.validators import DataRequired, Email

basedir = os.path.abspath(os.path.dirname(__file__))

app = Flask(__name__)
app.config['SECRET_KEY'] = 'I have a dream'
app.config['UPLOADED_PHOTOS_DEST'] = os.path.join(basedir, 'uploads') # you'll need to create a folder named uploads

photos = UploadSet('photos', IMAGES)
configure_uploads(app, photos)
patch_request_class(app)  # set maximum file size, default is 16MB


class UploadForm(FlaskForm):
    name = StringField('Name', [DataRequired()])
    email = StringField('Email', [Email(message='Not a valid email address.'), DataRequired()])
    photo = FileField(validators=[FileAllowed(photos, 'Image only!'), FileRequired('File was empty!')])
    submit = SubmitField('Upload')


@app.route('/', methods=['GET', 'POST'])
def upload_file():
    form = UploadForm()
    if form.validate_on_submit():
        filename = photos.save(form.photo.data)
        file_url = photos.url(filename)
    else:
        file_url = None
    return render_template('index.html', form=form, file_url=file_url)


if __name__ == '__main__':
    app.run()

我的html如下:

{% extends 'layout.html' %}

{% block styles %}
    <link rel="stylesheet" href="{{ url_for('static', filename='css/forms.css') }}" rel="stylesheet" type="text/css">
{% endblock %}


{% block content %}
<div class="formwrapper">
  <h2 class="title">Contact</h2>
  <form method="POST" action="/" enctype="multipart/form-data">
      <div class="form-field">{{ form.name.label }} {{ form.name(size=20) }}
      {% if form.name.errors %}
        <ul class="errors">
          {% for error in form.name.errors %}
            <li>{{ error }}</li>
          {% endfor %}
        </ul>
      {% endif %}
      </div>
      <div class="form-field">{{ form.email.label }} {{ form.email }}
      {% if form.email.errors %}
        <ul class="errors">
            {% for error in form.email.errors %}
                <li>{{ error }}</li>
            {% endfor %}
        </ul>
    {% endif %}
      </div>
       {{ form.hidden_tag() }}
     {{ form.photo }}
      {{ form.submit }}

  </form>
</div>
{% endblock %}

这不是一个超级复杂的程序,由于我是Flask的第一个实质性经验,所以我把这段代码混在一起。就html而言,这里还散布着一些小精灵。到目前为止,该程序仅上传带有文件名的文件。任何帮助表示赞赏。谢谢。

1 个答案:

答案 0 :(得分:1)

UploadSet.save()函数采用参数name,该参数应该为您提供所需的内容。

例如

photos.save(form.photo.data, name=f"{form.email.data}.jpg") 

注意:我不确定在这种情况下如何处理文件扩展名,因此您可能需要测试/调整它。