0

I create a API by fastAPI like the following:

@app.post('/uploadFile/')
async def uploadFile(file:UploadFile = File(...)):
    file_name,extension_file_name = os.path.splitext(file.filename)
    base_path = os.path.join(os.getcwd(),'static')
    path_cheked_exists = os.path.join(base_path,extension_file_name[1:])
    if not os.path.exists(path_cheked_exists):
        os.makedirs(path_cheked_exists)
    
    try:
        shutil.copy(file,path_cheked_exists)
    except Exception as exp:
        print("can not copy that file")

    return {'file':'okay'}

API returned the result but didn't save file .

Thanks for any help with shutil module

Dunguyen
  • 71
  • 1
  • 1
  • 8

1 Answers1

0

Instead of using shutil module, you can use a simple context manager

with open('filename.ext', 'wb+') as file_obj:
        file_obj.write(file.file.read())

Also your problem could be that you only wrote file. Try shutil.copy(file.file,path_cheked_exists)

HLX Studios
  • 213
  • 1
  • 3