@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
|
pip install fastapi uvicorn python-multipart |
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
|
uvicorn app:app --reload |
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.