PolarBear
PolarBear

Reputation: 39

Flask: How to read "file" from request.files multiple times?

For flask web app, I know I can't read a "file" multiple times from request.files because it's a stream. So when I read it once, I'll empty it. But I need to use the "file" multiple times without saving it locally and I'm having trouble doing it.

For example, from this

image = request.files["image"]

I'd like to have something like

image2 = image.copy

and perform different operations on image and image2.

Can someone please help me with this?

Upvotes: 2

Views: 2122

Answers (2)

Sourav Purkait
Sourav Purkait

Reputation: 344

image = request.files["image"]
# Seek the pointer to the beginning of the file to read again
request.files["image"].seek(0)

Upvotes: 5

Behrouz
Behrouz

Reputation: 51

After reading a file just run "f.stream.seek(0)" this points to the beginning of the file stream and then you are able to read the file from beginning again, you can simply put the following snippet in a loop and see it in action.

f.stream.seek(0)
stream = io.StringIO(f.stream.read().decode("UTF8"), newline=None)
reader = csv.reader(stream)
for row in reader:
    print(row)

Upvotes: 0

Related Questions