2

I have this simple code snippet that I use for File upload using FastAPI in Python.

@app.post("/uploadfile")
async def create_upload_file(file: UploadFile = File(...)):
    contents = await file.read()
    print(str(contents)[2:-1])
    with open(file.filename, "wb") as buffer:
        buffer.write(file.file.read())
    return {"filename": file.filename}

I tried this with my frontend React app and it works perfectly EXCEPT it doesn't save the data I receive. This code should get csv files and save them locally. As you can see, I print the contents from the file and the contents printed is correct but when I try to save it locally with buffer.write(file.file.read()), I just get the file created but there's no content in it aka is empty. Another note, when I print the contents I get the csv file as a string. Is there a way to fix this or I need to handle the string, convert it to csv and then write this data inside my created file?

anthino12
  • 770
  • 1
  • 6
  • 29

2 Answers2

4

File data once read is not available again. So, read it only once

Divakar Patil
  • 323
  • 2
  • 11
1

I just want to add corrections to your code to make it work well, and also I would recommend using async read-write library:

import aiofiles

@app.post("/uploadfile")
async def create_upload_file(file: UploadFile = File(...)):
    contents = await file.read()
    print(str(contents)[2:-1])
    async with aiofiles.open(file.filename, mode='wb') as f:
        await f.write(contents)
    return {"filename": file.filename}