I Met A Funny Issue With Flask’s FileStorage At Work Today
# Take Note if you’re working with Python Flask

So I was fixing a bug today at work.
Desired outcome — user uploads some file, and we save it in multiple directories without problem
Actual outcome — user uploads some file, and we save it in multiple directories. Said file appears in all directories. All but one file is empty.
How My Initial Code Was Like
Not gonna post my exact code cus Company policy and stuff. But this was what it kinda looked like:
for folder in folders:
file.save(folder)
# folder is a string value representing an actual folder path
# file is a FileStorage object Assuming I had 3 folders folder1 folder2 and folder3, the file did end up appearing in the folders.
folder1/file.txt folder2/file.txt folder3/file.txt
But only folder1/file.txt had stuff inside. folder2/file.txt and folder3/file.txt were just empty text files.
The Solution That Worked
for folder in folders:
file.stream.seek(0)
file.save(folder)After I added this line file.stream.seek(0), my code worked as intended. The file would still save in all relevant folders, but this time, the contents of each file would be correct.
Why the original code doesn’t work
for folder in folders:
file.save(folder)file can only .save() once. If we .save() it a second time (without the above workaround), it will simply save an empty file.
For some reason, there’s some sort of cursor inside file. And if we .save() it, the cursor goes to the end of file. And if we try to .save() it again, the cursor doesn’t move as it is already at the end! Leading to the empty file being saved.
What the solution does
for folder in folders:
file.stream.seek(0)
file.save(folder)The line file.stream.seek(0) resets the cursor back to the start of the file. So that whenever .save() happens, the cursor is at the start of the file, and all the content in the file gets written.
Moral of the story
I had lots of other stuff to handle, so I didn’t dig deep into why it was designed like this.
But if you’re working with Python Flask, and need to save a FileStorage object to multiple directories, remember to add the file.stream.seek(0) line.
Some Final words
If this story provided value and you wish to show a little support, you could:
- Clap 50 times for this story (this really, really helps me out)
- Sign up for a Medium membership using my link ($5/month to read unlimited Medium stories)
My Ebooks: https://zlliu.co/ebooks
My LinkedIn: https://www.linkedin.com/in/zlliu/
My Workspace Setup: https://zlliu.co/workspace






