3

I am trying to upload a PDF to FastAPI. After turning the PDF into a base64-blob and storing it in a txt-file, I POST this file to FastAPI using Postman.

This is my server-side code:

from fastapi import FastAPI, File, UploadFile
import base64

app = FastAPI()

@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
    contents = await file.read()
    blob = base64.b64decode(contents)
    pdf = open('result.pdf','wb')
    pdf.write(blob)
    pdf.close()
    return {"filename": file.filename}

This procedure works fine for a single-page PDF document of size 279KB (blob-size: 372KB), but it doesn't for a multi-page document of size 1.8MB (blob-size: 2.4MB).

When I try, I get the following WARNING and a 400 bad request response (along with the reseponse "detail": "There was an error parsing the body"): "Did not find boundary character 55 at index 2"

I'm sure there must be an explanation for this behavior? Maybe it has something to do with async?

Benji
  • 549
  • 7
  • 22
  • 1
    Does this answer your question? [How to Upload File using FastAPI?](https://stackoverflow.com/questions/63048825/how-to-upload-file-using-fastapi) – Chris Mar 18 '23 at 07:21

1 Answers1

1

This is most likely an issue with saving the file using open().

For large files pdf.close() will execute before pdf.write() has finished saving all the contents of the file.

In order to ensure the whole file being written before it is closed, use with such as this:

with open('failed.pdf', 'wb') as outfile:
    outfile.write(blob)

Using the with you will not need to close() after writing. with should also be considered best practice over saving the file into a local variable.

kacase
  • 1,993
  • 1
  • 18
  • 27