Cannot Upload File to FastAPI backend using JavaScript Fetch API in the frontend

As per the documentation:

Warning: When using FormData to submit POST requests using XMLHttpRequest or the Fetch_API with the
multipart/form-data Content-Type (e.g. when uploading Files and
Blobs to the server), do not explicitly set the Content-Type
header on the request. Doing so will prevent the browser from being
able to set the Content-Type header with the boundary expression
it will use to delimit form fields in the request body.

Hence, you should remove the Content-Type header from your code when sending the fetch request. The same applies to sending requests through Python Requests, as described here and here. Read more about the boundary in multipart/form-data.

Working examples on how to upload file(s) using FastAPI in the backend and Fetch API in the frontend can be found here, here, as well as here, here and here.

Leave a Comment