Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

fastapi upload file save

import shutil
from pathlib import Path
from tempfile import NamedTemporaryFile
from typing import Callable

from fastapi import UploadFile


def save_upload_file(upload_file: UploadFile, destination: Path) -> None:
    try:
        with destination.open("wb") as buffer:
            shutil.copyfileobj(upload_file.file, buffer)
    finally:
        upload_file.file.close()


def save_upload_file_tmp(upload_file: UploadFile) -> Path:
    try:
        suffix = Path(upload_file.filename).suffix
        with NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
            shutil.copyfileobj(upload_file.file, tmp)
            tmp_path = Path(tmp.name)
    finally:
        upload_file.file.close()
    return tmp_path


def handle_upload_file(
    upload_file: UploadFile, handler: Callable[[Path], None]
) -> None:
    tmp_path = save_upload_file_tmp(upload_file)
    try:
        handler(tmp_path)  # Do something with the saved temp file
    finally:
        tmp_path.unlink()  # Delete the temp file
Comment

how to save upload file in fastapi

from fastapi import FastAPI, File, UploadFile

app = FastAPI()


@app.post("/upload-file/")
async def create_upload_file(uploaded_file: UploadFile = File(...)):
    file_location = f"files/{uploaded_file.filename}"
    with open(file_location, "wb+") as file_object:
        file_object.write(uploaded_file.file.read())
    return {"info": f"file '{uploaded_file.filename}' saved at '{file_location}'"}
Comment

PREVIOUS NEXT
Code Example
Python :: adding to python path 
Python :: how to make python code faster 
Python :: beautifulsoup import 
Python :: python def 
Python :: django error handling < form 
Python :: numpy fill with 0 
Python :: creating dataframe 
Python :: BURGERS2 codechef solution 
Python :: python function with two parameters 
Python :: apply on dataframe access multiple columns 
Python :: temp python web server 
Python :: python abc 
Python :: unsupervised learning 
Python :: combine dictionaries, values to list 
Python :: check for prime in python 
Python :: count repeated strings map python 
Python :: plot multiindex columns pandas 
Python :: write in entry() in tkinter 
Python :: django pagination rest framework 
Python :: Highlight Active Links in Django Website 
Python :: arrayfield django example 
Python :: python opencv load image 
Python :: RuntimeError: dictionary changed size during iteration 
Python :: change password django 
Python :: python how to add to a list 
Python :: bitwise and python image 
Python :: python one line if without else 
Python :: get current url with parameters url django 
Python :: read pickle file 
Python :: lambda and function in python 
ADD CONTENT
Topic
Content
Source link
Name
8+2 =