1

I am trying to get and save several files from request in Flask using MultipleFileField. 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. What can I do to fix this problem?

GoshkaLP
  • 137
  • 1
  • 11

1 Answers1

0

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. 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())