Upload file using fastapi

Aric picture Aric · Jul 23, 2020 · Viewed 9k times · Source

I am using fastapi to upload file according to the official doc, just like:

@app.post("/create_file/")
async def create_file(file: UploadFile=File(...)):
      file2store = await file.read()
      # some code to store the BytesIO(file2store) to the other database

when I send a request using python requests lib:

f = open(".../file.txt", 'rb')
files = {"file": (f.name, f, "multipart/form-data")}
requests.post(url="SERVER_URL/create_file", files=files)

The file2store is always empty. Sometimes (rarely seen), it can get the file bytes, but almost all the time it is empty, so I can't to restore the file on the other database. I also tried the 'bytes' rather than 'UploadFile', I get the same results. Is there somewhere wrong in my code, or is the way I use the fastapi to upload file wrong?I google it for some answers for a long time, but failed. So I raise the problem here, Hoping someone who knows the answer can help me out. Thanks

Answer

mohd sakib picture mohd sakib · Nov 19, 2020
@app.post("/create_file/")
async def image(image: UploadFile = File(...)):
    print(image.file)
    # print('../'+os.path.isdir(os.getcwd()+"images"),"*************")
    try:
        os.mkdir("images")
        print(os.getcwd())
    except Exception as e:
        print(e) 
    file_name = os.getcwd()+"/images/"+image.filename.replace(" ", "-")
    with open(file_name,'wb+') as f:
        f.write(image.file.read())
        f.close()
   file = jsonable_encoder({"imagePath":file_name})
   new_image = await add_image(file)
   return {"filename": new_image}