使用FileField wtforms上传文件时,将文件名存储在列中

时间:2018-11-16 17:08:36

标签: python flask

我有一个使用以下代码的表,其中包括两列:名称和文件名。我的问题是当我上传文件时,其文件名存储在文件名列中。我该怎么做呢? 现在,当我上传文件时,“ None”放在文件名中。我只能上传文件或在数据库中输入名称,我认为问题是enctype =“ multipart / form-data”。     从flask_wtf导入FlaskForm

from flask_wtf.file import FileField
from wtforms import StringField,SelectField,IntegerField
from wtforms.ext.sqlalchemy.fields import QuerySelectField
from wtforms.validators import DataRequired, Email, Length
class ContactForm(FlaskForm):

    name = IntegerField('name', validators=[Length(min=-1, max=100, message='You cannot have more than 100 characters')])
    filename = FileField()

这是我的app.py:

def new_contact():
    '''
    Create new contact
    '''
    form = ContactForm()


    if  form.validate_on_submit():


        return render_template('web/new_contact.html',form = form)

        f = form.filename.data
        f.save(os.path.join("./static/upload/", f.filename))
        return redirect(url_for('new_contact'))
        print(f)



        my_contact = Contact()
        form.populate_obj(my_contact)
        db.session.add(my_contact)
        try:
            db.session.commit()
            # User info
            flash('Contact created correctly', 'success')
            return redirect(url_for('contacts'))
        except:
            db.session.rollback()
            flash('Error generating contact.', 'danger')

    return render_template('web/new_contact.html', form=form)

1 个答案:

答案 0 :(得分:1)

鉴于您提供的信息有限,我将尝试实现所需的功能。

您的ContactForm可以这样呆着:

class ContactForm(FlaskForm):

    name = IntegerField('File Name', validators=[Length(min=-1, max=100, message='You cannot have more than 100 characters')])
    filename = FileField()

然后您将表单对象从自定义烧瓶路径传递到模板,为了进行说明,将其称为联系路径

@app.route('/contact')
def contact():
    contact_form = ContactForm()
    return render_template('contact.html'
                            contact_form = contact_form)

在本示例contact.html中调用的模板中,您呈现了表单:

<form action="" method="post" enctype="multipart/form-data">
    {{ contact_form.csrf_token }}
    {{ contact_form.name }}
    {{ contact_form.filename}}
    <input type="submit"/>
</form>

在这种形式下,我们希望使用action=""在同一路径(即联系路径)上发布数据。因此,在此示例中,我们还应该使用flask app的contact()方法验证数据。但是您可能想知道的enctype="multipart/form-data"是什么?

第一个搜索结果是什么给了我们结果:

  

enctype属性指定将表单数据提交到服务器时应如何编码。   注意:仅当method =“ post”时,才能使用enctype属性。

对于multipart/form-data

  

没有字符被编码。当您使用具有文件上传控件的表单时,此值是必需的。

最后,我们像这样更新烧瓶应用程序联系路线

@app.route('/contact')
def contact():
    contact_form = ContactForm()
    if form.validate_on_submit():
        f = contact_form.filename.data
        name = contact_form.name.data
        f.save(os.path.join("./static/contacts/", name))
        redirect(url_for('contact'))
    return render_template('contact.html'
                            contact_form = contact_form)

我们已经成功地从表单中收集了数据,并使用表单中的名称将文件静态保存在通讯录文件夹中。也许我们还可以使用secure_filename中的werkzeug.utils