ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • FastAPI 시리즈 10화 - 파일 업로드 및 다운로드 기능 구현하기
    언어 및 프레임워크/FastAPI 2025. 5. 13. 19:32
    728x90

    FastAPI에서 단일 파일, 멀티 파일 업로드와 파일 다운로드 API를 구현하는 방법을 예제 중심으로 정리합니다. 업로드 용량 제한, MIME 타입 설정 등 실무 적용 팁도 포함합니다.


    파일 처리, REST API에서 왜 중요한가?

    웹 서비스에서 파일을 다루는 기능은 매우 일반적입니다:

    • 사용자 프로필 사진 업로드
    • 문서 첨부 및 다운로드
    • 이미지, PDF 등 대용량 파일 처리

    FastAPI는 File, UploadFile, FileResponse를 활용해
    간단하면서도 강력하게 파일 처리 API를 구성할 수 있습니다.


    1. 단일 파일 업로드 처리

    from fastapi import FastAPI, File, UploadFile
    
    app = FastAPI()
    
    @app.post("/uploadfile/")
    async def upload_file(file: UploadFile = File(...)):
        content = await file.read()
        return {"filename": file.filename, "size": len(content)}
    
    • UploadFile은 비동기로 파일을 스트리밍 처리 (메모리 효율적)
    • file.filename, file.content_type 등 메타데이터 확인 가능
    • 파일 데이터는 await file.read()로 읽을 수 있음

    2. 멀티 파일 업로드

    from typing import List
    
    @app.post("/upload-multiple/")
    async def upload_multiple(files: List[UploadFile] = File(...)):
        return {"filenames": [file.filename for file in files]}
    
    • 다수의 파일을 한 번에 업로드 가능
    • Swagger UI에서 다중 파일 선택 기능 제공
    • 실무에서는 첨부 파일 다중 등록 등에 활용

    3. 업로드 파일 저장 예제

    @app.post("/save-file/")
    async def save_file(file: UploadFile = File(...)):
        with open(f"./{file.filename}", "wb") as buffer:
            content = await file.read()
            buffer.write(content)
        return {"message": f"{file.filename} 저장 완료"}
    
    • 파일을 서버 로컬 디렉토리에 저장
    • 주의: 반드시 저장 경로를 검증 (보안상 중요)

    4. 파일 다운로드 API

    from fastapi.responses import FileResponse
    
    @app.get("/download/{filename}")
    def download_file(filename: str):
        file_path = f"./{filename}"
        return FileResponse(path=file_path, filename=filename, media_type='application/octet-stream')
    
    • 클라이언트에서 Content-Disposition: attachment로 파일 다운로드 가능
    • media_type을 조절해 이미지, PDF 등 다양한 파일 타입 대응 가능

    5. 업로드 시 최대 용량 제한 설정

    Uvicorn 또는 ASGI 서버 레벨에서 제한 가능
    (예: Uvicorn 실행 시 10MB 제한)

    uvicorn app:app --limit-concurrency 1 --limit-max-request-size 10485760
    
    • --limit-max-request-size: 바이트 단위 (10MB = 10 * 1024 * 1024)

    실제 서비스에서는 반드시 업로드 용량 제한을 설정해야 DoS 공격 등을 방지할 수 있습니다.


    6. 실무 보안 고려사항

    • 파일 이름 검증: 절대 경로로 저장하지 않도록 방지 (os.path.basename() 활용 추천)
    • 파일 타입 검증: file.content_type으로 MIME 타입 확인
    • 서버 저장 위치 관리: 파일 업로드 폴더와 서비스 실행 폴더 분리 권장

    정리 – FastAPI의 파일 처리 기능, 실무에서도 즉시 활용 가능

    기능 방법

    단일 파일 업로드 UploadFile = File(...)
    멀티 파일 업로드 List[UploadFile] = File(...)
    파일 저장 await file.read() + 파일 쓰기
    파일 다운로드 FileResponse()
    업로드 제한 Uvicorn --limit-max-request-size 옵션
    보안 고려 파일명, 타입 검증 필수

    FastAPI의 파일 업로드 및 다운로드 기능은 가볍고 직관적이면서
    대용량 서비스에서도 충분히 실전 적용이 가능합니다.


    다음 글 예고

    FastAPI 시리즈 11화 - OAuth2 이해와 FastAPI 로그인 인증 시스템 구축
    에서는 FastAPI로 OAuth2 기반 사용자 인증 로직을 어떻게 구현하는지,
    토큰 기반 인증 시스템과 실무 적용 전략을 다룹니다.

    728x90
Designed by Tistory.