Skip to content

Instantly share code, notes, and snippets.

@zspine
Last active November 10, 2023 02:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zspine/90195112570a546bdb055d771ce58781 to your computer and use it in GitHub Desktop.
Save zspine/90195112570a546bdb055d771ce58781 to your computer and use it in GitHub Desktop.
Detecting File Mime Types in FastAPI Using the Python Magic Library
"""
Using `magic` library to detect the MIME type of uploaded files.
"""
from typing import Annotated
from fastapi import FastAPI, File, UploadFile, APIRouter
import magic
app = FastAPI()
#router = APIRouter()
@app.post("/files/", tags=["contrib"])
#@router.post("/files/", tags=["contrib"])
async def create_file(file: Annotated[bytes, File()]):
return {"file_size": len(file)}
@app.post("/uploadfile/", tags=["contrib"])
#@router.post("/uploadfile/", tags=["contrib"])
async def create_upload_file(file: UploadFile):
buffer = file.file.read(1024)
mime_type = magic.from_buffer(buffer, True)
file.file.seek(0)
return {"filename": file.filename, "mime": mime_type}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment