Click here to Skip to main content
15,887,267 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to upload multiple images by FastAPI and convert it to grey scale images.
so I have written the following code but it throws some error :

File "C:\Users\SMRUTI\Desktop\grey\.\multi.py", line 17, in upload_images
with open(f'{file.filename}',"wb") as buffer:
AttributeError: 'list' object has no attribute 'filename'

What I have tried:

from typing import List
from PIL import Image
from fastapi import FastAPI, File, UploadFile
from fastapi.responses import FileResponse
import shutil
from werkzeug.utils import secure_filename

app = FastAPI()
async def get_image(file):
    filename = secure_filename(file.filename)
    with open(filename,"wb") as buffer:
        shutil.copyfileobj(file.file, buffer)
    return filename

@app.post("/uploadfiles/")
async def upload_images(file: List[UploadFile] = File(...),):
    with open(f'{file.filename}',"wb") as buffer:
            shutil.copyfileobj(file.file,buffer)
    return FileResponse (file.filename)

@app.post("/grey_image/")
async def create_grey_img(file:list[UploadFile]):
    filename= await get_image(file)
    img = Image.open(filename)
    img.convert('L').save('grey_img.jpg')
    return FileResponse("grey_img.jpg")
Posted
Updated 17-Jul-22 7:38am
v2

The message is quite clear, you are trying to refer to a filename attribute in the file List. There is no such attribute; Check the documentation for the List type.
 
Share this answer
 
Have a look at this Python FastAPI Upload File | Upload Multiple File using FastAPI - TutorialsBuddy[^]

and there is a few things on your code

Quote:
async def upload_images(file: List[UploadFile] = File(...),):


why the trailing comma?

Quote:
async def create_grey_img(file:list[UploadFile]):


list should be an upper case L

you need to iterate over the List of files that you are taking in i.e.
Python
for single_file in file:
  # do stuff here
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900