3

I need to upload an image file to a certain folder. It works fine on localhost but if I push the app to heroku it tells me:

IOError: [Errno 2] No such file or directory: 'static/userimg/1-bild-1.jpg'

Which means it cant find the folder?

I need to store the image files there for a few seconds to perform some actions on theme. After that they will be sent to AWS and will be deleted from the folder.

Thats the code where I save the images into the folder:

i = 1
for key, file in request.files.iteritems():
    if file:
        filename = secure_filename(str(current_user.id) + "-bild-"+ str(i) +".jpg")
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) 
        i = i + 1 

Later I get the files from the folder like this:

for item in os.listdir(os.path.join(app.config['UPLOAD_FOLDER'])):
    if item.startswith(str(current_user.id)) and item.split(".")[0].endswith("1"):
        with open(os.path.join(app.config['UPLOAD_FOLDER'], item), "rb") as thefile:
            data = base64.b64encode(thefile.read())
            upload_image_to_aws_from_image_v3('MYBUCKET', "userimg/", data, new_zimmer, "hauptbild", new_zimmer.stadt, new_zimmer.id)
        os.remove(str(thefile.name))

That is the upload folder in app config:

UPLOAD_FOLDER = "static/userimg/"

Everything works fine on localhost.

Roman
  • 3,563
  • 5
  • 48
  • 104

1 Answers1

0

I had to add the absolute path to the directory, because the path on the server is different.

You can run heroku run bash for your app through the CLI and check the directories with dir. Use then cd .. to go back or cd *directory name* to go into the directory.

I had to add

MYDIR = os.path.dirname(__file__)

and replace all

os.path.join(app.config['UPLOAD_FOLDER']

with

os.path.join(MYDIR + "/" + app.config['UPLOAD_FOLDER']

Some informations on the topic also here: Similar question

Roman
  • 3,563
  • 5
  • 48
  • 104
  • Note that uploaded files will be discarded upon redeploying the app, or latest after 24 hours. See the documentation: https://devcenter.heroku.com/articles/active-storage-on-heroku – Michael Schmid Dec 06 '21 at 22:21