576i
576i

Reputation: 8362

How to upload a single file to FastAPI server using CURL

I'm trying to set up a FastAPI server that can receive a single file upload from the command line using curl.

I'm following the FastAPI Tutorial here:

https://fastapi.tiangolo.com/tutorial/request-files/?h=upload+file

from typing import List
from fastapi import FastAPI, File, UploadFile
from fastapi.responses import HTMLResponse
app = FastAPI()

@app.post("/file/")
async def create_file(file: bytes = File(...)):
     return {"file_size": len(file)}

@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
    return {"filename": file.filename}

@app.post("/files/")
async def create_files(files: List[bytes] = File(...)):
    return {"file_sizes": [len(file) for file in files]}

@app.post("/uploadfiles/")
async def create_upload_files(files: List[UploadFile] = File(...)):
    return {"filenames": [file.filename for file in files]}

Running this code and then opening "http://127.0.0.1:5094" in a browser gives me a upload form with four ways of selecting files and uploading

I followed this tutorial: https://medium.com/@petehouston/upload-files-with-curl-93064dcccc76

I tried uploading a file "1.json" in the current directory like this

curl -F "[email protected]" http://127.0.0.1:5094/uploadfiles

on the server side I get this result

INFO:     127.0.0.1:58772 - "POST /uploadfiles HTTP/1.1" 307 Temporary Redirect

I do not understand why a redirect happens.

I need help on how to either guess the correct curl syntax or fix this on the FastAPI side.

Upvotes: 8

Views: 6375

Answers (1)

576i
576i

Reputation: 8362

The solution was to tell curl to follow a redirect.

curl -L -F "[email protected]" http://127.0.0.1:5094/uploadfile

which then uploads the file.

Upvotes: 4

Related Questions