-1

I try to write the file to disk by specifying the path to the folder to save. But I get the error of reading the file by the specified path.

FileNotFoundError: [Errno 2] No such file or directory: '/home/jekson/Projects/img-text-reco/static/product_images/24f2a9d0372a49bc8c5eb259798477f0.jpeg'

Error occurs in this line.

async with aiofiles.open(os.path.join(IMG_DIR, file_name)) as f

For clarity, I made a print call indicating the paths in the body function

from db import BASEDIR

print(BASEDIR) # /home/jekson/Projects/img-text-reco

def file_upload():
    ....
    IMG_DIR = os.path.join(BASEDIR, 'static/product_images')
    if not os.path.exists(IMG_DIR):
        os.makedirs(IMG_DIR)
    print(f'IMG_DIR {IMG_DIR}') # IMG_DIR /home/jekson/Projects/img-text-reco/static/product_images
    content = await file.read()
    if file.content_type not in ['image/jpeg', 'image/png']:
        raise HTTPException(status_code=406, detail="Only .jpeg or .png  files allowed")
    file_name = f'{uuid.uuid4().hex}{ext}'
    print(os.path.join(IMG_DIR, file_name)) # /home/jekson/Projects/img-text-reco/static/product_images/24f2a9d0372a49bc8c5eb259798477f0.jpeg
    async with aiofiles.open(os.path.join(IMG_DIR, file_name)) as f:
        await f.write(content)
    path_to_img = os.path.abspath(os.path.join(IMG_DIR, file_name))
    ....
Smack Alpha
  • 1,828
  • 1
  • 17
  • 37
Jekson
  • 2,892
  • 8
  • 44
  • 79

1 Answers1

1

You open the file for reading and it doesn't exist, hence the error. The following f.write suggests that you want to open the file for writing instead:

async with aiofiles.open(os.path.join(IMG_DIR, file_name), mode='w') as f:
a_guest
  • 34,165
  • 12
  • 64
  • 118
  • That's right. Didn't catch that. Thank you! In my case, I' ll have to use `wb`instead of `w`. – Jekson Jul 29 '20 at 10:15