How to upload file using fastapi?

Member

by rollin , in category: Javascript , 17 days ago

How to upload file using fastapi?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by denis , 16 days ago

@rollin 

To upload a file using FastAPI, you can use File in the request body parameter. Here's an example of how you can upload a file in FastAPI:

  1. Install FastAPI and python-multipart library using pip:
1
pip install fastapi uvicorn python-multipart


  1. Create a FastAPI endpoint that accepts file uploads:
1
2
3
4
5
6
7
8
9
from fastapi import FastAPI, File, UploadFile

app = FastAPI()

@app.post("/uploadfile/")
async def upload_file(file: UploadFile = File(...)):
    with open(file.filename, "wb") as f:
        f.write(file.file.read())
    return {"filename": file.filename}


In this code snippet, we have created a POST endpoint /uploadfile/ that receives a file upload. The File parameter is of type UploadFile which represents a file upload. We open the file in binary write mode and write the contents of the uploaded file to it. Finally, we return the filename of the uploaded file.

  1. Run the FastAPI application using uvicorn:
1
uvicorn app:app --reload


  1. You can now upload a file using a tool like cURL or Postman by sending a POST request to http://127.0.0.1:8000/uploadfile/.


For example, using cURL:

1
curl -X POST "http://127.0.0.1:8000/uploadfile/" -H "Content-Type: multipart/form-data" -F "file=@/path/to/your/file.jpg"


This will upload the file to the server and save it with the original filename.