通过 flask 和 wtforms MultipleFileField 保存多个文件
Saving multiple files through flask and wtforms MultipleFileField
我正在尝试使用 MultipleFileField 从 Flask 中的请求获取并保存多个文件。但问题是我无法遍历它。我的意思是:
表格 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')
并查看代码:
form = TestForm()
...
files = form.files
for file in files:
with open(path.join('some_path', file.filename), 'wb') as f:
f.write(file.read())
我收到了这么大的请求:
["<_io.BufferedReader name='1.jpg'>", "<_io.BufferedReader name='2.jpg'>"]
但我收到错误消息:
AttributeError: 'str' object has no attribute 'filename'
因此它将 io.BufferedReader
转换为 str
。我该怎么做才能解决这个问题?
您的 'file' 是一个字符串,在 with 语句之前将其切片并保存到文件名变量中,然后仅在 with 语句中包含 'filename' 。类似于:
form = TestForm()
...
files = form.files.data
for file in files:
with open(path.join('some_path', file), 'wb') as f:
f.write(file.read())
我正在尝试使用 MultipleFileField 从 Flask 中的请求获取并保存多个文件。但问题是我无法遍历它。我的意思是:
表格 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')
并查看代码:
form = TestForm()
...
files = form.files
for file in files:
with open(path.join('some_path', file.filename), 'wb') as f:
f.write(file.read())
我收到了这么大的请求:
["<_io.BufferedReader name='1.jpg'>", "<_io.BufferedReader name='2.jpg'>"]
但我收到错误消息:
AttributeError: 'str' object has no attribute 'filename'
因此它将 io.BufferedReader
转换为 str
。我该怎么做才能解决这个问题?
您的 'file' 是一个字符串,在 with 语句之前将其切片并保存到文件名变量中,然后仅在 with 语句中包含 'filename' 。类似于:
form = TestForm()
...
files = form.files.data
for file in files:
with open(path.join('some_path', file), 'wb') as f:
f.write(file.read())