Forums

Can't upload file in a Flask app

Hello there,

I just published an app on pythonanywhere, where you can post articles with an optional picture.

Whenever I submit the new_post form with a picture in it, I get an error 500, in logs I see for example:

FileNotFoundError: [Errno 2] No such file or directory: 'myapp/uploads/2020-10-07 15-21-54.115117.jpg'

The flask route which is responsible of uploading pictures is in /home/myself/myapp/myapp/routes.py:

picture.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

And this UPLOAD_FOLDER is set in /home/myself/myapp/config.py

Where am I wrong?? Is there any file permission that needs to be changed in order to write into the myapp/myapp/uploads folder?

Thanks by advance. Benjamin

Are you sure that that really is the value of UPLOAD_FOLDER? The error message has a relative path in it (that is, one that does not start with /).

If you put this in your code just before the call to picture.save then you'll see the output in the website's server log (linked from the "Web" page) and that might help track down what the problem is:

 :::python
 print(f"UPLOAD_FOLDER is {UPLOAD_FOLDER!r}", flush=True)

As you advised, I logged the folder with print(f"UPLOAD_FOLDER is {app.config['UPLOAD_FOLDER']!r}", flush=True), which results in :

UPLOAD_FOLDER is 'crommunity/uploads'

Maybe I'm supposed to append app.root_path or something that represents the absolute path of my app?

Solved! I changed my saving path to this :

picture.save(os.path.join(app.root_path, app.config['UPLOAD_FOLDER'], filename))

and updated the config.py and it works. Thanks for your time!

Good to see that you sorted it out!

@bnthor 2 years on and your post is still saving lives. Thank you so much, I had the same issue and it has been resolved following your method.

Thanks for confirming that! Just to add some context: all paths in the web apps will be relative to the Working directory path set on the Web page (by default it's the user's home directory: /home/username) -- in the server log, in the section where WSGI logs after reloading the web app, you can spot a phrase "current working directory: ...". To ensure that paths in your web app work correctly, you need either to change the value of the Working directory (and reload the webapp), and keep it consistent in your code, or provide the absolute paths.