All about

To check the extension of a file received through UploadFile in FastAPI using Python3, you can use the following code. This code extracts the file extension from the filename, compares it with a list of allowed extensions, and raises an HTTPException if the extension is not allowed.

from fastapi import FastAPI, UploadFile, File, HTTPException

app = FastAPI()

ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
    if not allowed_file(file.filename):
        raise HTTPException(status_code=400, detail="Invalid file extension. Allowed extensions are txt, pdf, png, jpg, jpeg, gif.")
    
    # Add your file processing code here.
    # For example, you can save the file or perform other operations.
    
    return {"filename": file.filename}

 

In this code, the allowed_file function extracts the file extension from the filename and checks if it is in the list of allowed extensions. If the extension is not allowed, it raises an HTTP 400 error with a corresponding error message. Otherwise, you can add your specific file processing logic in the designated section. The ALLOWED_EXTENSIONS variable contains the list of allowed extensions, and you can modify it according to your requirements.

공유하기

facebook twitter kakaoTalk kakaostory naver band
loading