简体   繁体   English

通过flask和wtforms MultipleFileField保存多个文件

[英]Saving multiple files through flask and wtforms MultipleFileField

I am trying to get and save several files from request in Flask using MultipleFileField.我正在尝试使用 MultipleFileField 从 Flask 中的请求获取和保存多个文件。 But the problem is that I can't iterate through it.但问题是我无法遍历它。 What I mean:我的意思是:
Form class表单类

class TestForm(FlaskForm):
    user_id = IntegerField('user_id', validators=[DataRequired()])
    name = StringField('name', validators=[DataRequired()])
    description = StringField('description', validators=[DataRequired()])
    category_id = IntegerField('category_id', validators=[DataRequired()])
    date_of_purchase = DateField('date_of_purchase', validators=[DataRequired()])
    guarantee_period = IntegerField('guarantee_period', validators=[DataRequired()])
    files = MultipleFileField('files')

And view code:并查看代码:

form = TestForm()
...
files = form.files
for file in files:
   with open(path.join('some_path', file.filename), 'wb') as f:
        f.write(file.read())

I get this massive in request:我收到了这么大的请求:

["<_io.BufferedReader name='1.jpg'>", "<_io.BufferedReader name='2.jpg'>"]

But I get the error:但我收到错误:

AttributeError: 'str' object has no attribute 'filename'

So it converts io.BufferedReader to str .所以它将io.BufferedReader转换为str What can I do to fix this problem?我能做些什么来解决这个问题?

Your 'file' is a string, slice it before the with statement and save to a filename variable, then include just 'filename' inside the with statement.您的“文件”是一个字符串,在 with 语句之前将其切片并保存到文件名变量中,然后在 with 语句中只包含“文件名”。 Something like:就像是:

form = TestForm()
...
files = form.files.data
for file in files:
   with open(path.join('some_path', file), 'wb') as f:
        f.write(file.read())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM