Fastapi: [Question] Is there any proper way to upload files

Created on 14 Dec 2020  路  3Comments  路  Source: tiangolo/fastapi

Is there any proper way to upload files and configure paths like in Flask ?

UPLOAD_FOLDER = '/path/to/the/uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

(https://flask.palletsprojects.com/en/1.1.x/patterns/fileuploads/)

question

Most helpful comment

Because you are able to save the file async right now, Flask doesn't provide you an alternative. In FastAPI it is totally up to you, you can either use a coroutine or a function. Since you can use coroutine you can also use libraries like aiofiles.

import aiofiles

@app.post("/uploadfile/")
async def cache_favicon(file: UploadFile = File(...)):
    async with aiofiles.open("destination.jpg" , "wb") as f:
        await f.write(await file.read())

All 3 comments

Yeah, but for saving the files now I'm using shutil

for idx, img in enumerate(images):
    with open(str(idx)+".jpg", "wb") as buffer:
        shutil.copyfileobj(img.file, buffer)

Because you are able to save the file async right now, Flask doesn't provide you an alternative. In FastAPI it is totally up to you, you can either use a coroutine or a function. Since you can use coroutine you can also use libraries like aiofiles.

import aiofiles

@app.post("/uploadfile/")
async def cache_favicon(file: UploadFile = File(...)):
    async with aiofiles.open("destination.jpg" , "wb") as f:
        await f.write(await file.read())
Was this page helpful?
0 / 5 - 0 ratings