'FastAPI error uploading files bigger than 100kb

I am trying to create an endpoint for uploading files. However, if the file is bigger than 100Kb I am getting an error of 400 Bad Request. My guess is that it does not have enough time to upload the file.

The code of my function is like this:

import uvicorn
from fastapi import FastAPI, File, UploadFile
import pathlib

app = FastAPI(title='Tool', description='Tool descr', version='0.0.1')

uploads = 'uploads'
uploads_dir = pathlib.Path(os.getcwd(), uploads)

@app.post('/api/upload/')
async def upload_file(file: UploadFile=File(...)):
    """
    Upload the file to be processed.
    """
    print(file)
    async with aiofiles.open(file.file, 'rb') as fin:
        exfile = fin.read() 
    file_name = pathlib.Path(uploads_dir, file.filename)
    async with aiofiles.open(f'{file_name}', 'wb') as f:
        await f.write(exfile)
    return {'filename': file.filename, 
                'content-type': file.content_type}

if __name__ == '__main__':
    uvicorn.run('main:app', host='127.0.0.1', port=5003, log_level='info')   

So the server gives me a Bad Request answer with "did not find CR at end of boundary" if is a text file or if it is a binary file "Did not find boundary character 198 at index 2, fo rexample.

Error in Postman: { "detail": "There was an error parsing the body" }

The error that the server is returning is basically this:

Did not find boundary character 145 at index 2
[32mINFO[0m:     127.0.0.1:58032 - "[1mPOST /api/upload/ HTTP/1.1[0m" [31m400 Bad Request[0m
[33mWARNING[0m:  Invalid HTTP request received.
[32mINFO[0m:     127.0.0.1:58033 - "[1mPOST /api/upload HTTP/1.1[0m" [33m307 Temporary Redirect[0m
<starlette.datastructures.UploadFile object at 0x000001CCCF62AE80>
[32mINFO[0m:     127.0.0.1:58033 - "[1mPOST /api/upload/ HTTP/1.1[0m" [32m200 OK[0m
[32mINFO[0m:     127.0.0.1:58156 - "[1mPOST /api/upload HTTP/1.1[0m" [33m307 Temporary Redirect[0m
<starlette.datastructures.UploadFile object at 0x000001CCCF62E7F0>
[32mINFO[0m:     127.0.0.1:58156 - "[1mPOST /api/upload/ HTTP/1.1[0m" [32m200 OK[0m
[32mINFO[0m:     127.0.0.1:58190 - "[1mPOST /api/upload HTTP/1.1[0m" [33m307 Temporary Redirect[0m
Did not find CR at end of boundary (54)
[32mINFO[0m:     127.0.0.1:58191 - "[1mPOST /api/upload/ HTTP/1.1[0m" [31m400 Bad Request[0m

This are a few requests, some were successful (aprox 50k of size of the files) and the others were not processed as a "Bad Request".



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source