fastapi upload file 기능 구현

fastapi에서 upload file 기능을 구현했다. 간단히 endpoint를 만들고 postman으로 실제 잘 동작하는지 확인할 수 있다.

upload multiple files example

여러 파일을 업로드 하기 위해 다음과 같은 코드를 작성한다.

from fastapi import FastAPI, File, UploadFile
from typing import List
import os

app = FastAPI()

@app.get("/")
def read_root():
	return { "Hello": "World" }

@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(...)):
    UPLOAD_DIRECTORY = "./"
    for file in files:
        contents = await file.read()
        with open(os.path.join(UPLOAD_DIRECTORY, file.filename), "wb") as fp:
            fp.write(contents)
        print(file.filename)
    return {"filenames": [file.filename for file in files]}

FastAPI 서버 실행

uvicorn main:app --reload --host=0.0.0.0 --port=8000

Postman으로 upload 테스트

postman에서 보내는 request 타입을 POST로 하고 body를 form-data 형태로 하여 파일을 선택 후 send를 클릭한다.

FastAPI 서버에서 200 OK메시지가 출력되고 파일이 저장된 것이 보이면 정상 수행 된 것이다.

참고

Leave a Reply