upload multiple files
This commit is contained in:
@@ -46,20 +46,39 @@ def delete_celebrity(celebrity_id: int, db: Session = Depends(get_db)):
|
||||
|
||||
# --- NUOVI ENDPOINT PER LE IMMAGINI ---
|
||||
|
||||
@router.post("/{celebrity_id}/images", response_model=schemas.Image, status_code=201)
|
||||
def upload_celebrity_image(celebrity_id: int, file: UploadFile = File(...), db: Session = Depends(get_db)):
|
||||
@router.post("/{celebrity_id}/images", response_model=List[schemas.Image], status_code=201)
|
||||
def upload_celebrity_images(celebrity_id: int, files: List[UploadFile] = File(...), db: Session = Depends(get_db)):
|
||||
db_celebrity = crud.get_celebrity(db, celebrity_id=celebrity_id)
|
||||
if db_celebrity is None:
|
||||
raise HTTPException(status_code=404, detail="Celebrity not found")
|
||||
|
||||
file_extension = file.filename.split('.')[-1]
|
||||
unique_filename = f"{uuid.uuid4()}.{file_extension}"
|
||||
file_location = f"uploads/{unique_filename}"
|
||||
created_images = []
|
||||
for file in files:
|
||||
try:
|
||||
file_extension = file.filename.split('.')[-1]
|
||||
if not file_extension: # Gestisce file senza estensione
|
||||
file_extension = "jpg" # Default
|
||||
|
||||
unique_filename = f"{uuid.uuid4()}.{file_extension}"
|
||||
file_location = f"uploads/{unique_filename}"
|
||||
|
||||
with open(file_location, "wb+") as file_object:
|
||||
shutil.copyfileobj(file.file, file_object)
|
||||
with open(file_location, "wb+") as file_object:
|
||||
shutil.copyfileobj(file.file, file_object)
|
||||
|
||||
db_image = crud.create_celebrity_image(db=db, celebrity_id=celebrity_id, file_path=unique_filename)
|
||||
created_images.append(db_image)
|
||||
|
||||
except Exception as e:
|
||||
# Se un file fallisce, potremmo voler continuare con gli altri,
|
||||
# ma per ora lanciamo un'eccezione per l'intero batch.
|
||||
# In un'app di produzione, si potrebbe restituire una risposta parziale.
|
||||
print(f"Failed to upload file {file.filename}: {e}")
|
||||
raise HTTPException(status_code=500, detail=f"Could not upload file: {file.filename}")
|
||||
|
||||
return crud.create_celebrity_image(db=db, celebrity_id=celebrity_id, file_path=unique_filename)
|
||||
if not created_images:
|
||||
raise HTTPException(status_code=400, detail="No files were successfully uploaded.")
|
||||
|
||||
return created_images
|
||||
|
||||
@router.post("/{celebrity_id}/images/from-url", response_model=schemas.Image, status_code=201)
|
||||
async def add_image_from_url(celebrity_id: int, request: schemas.ImageUrlRequest, db: Session = Depends(get_db)):
|
||||
|
||||
Reference in New Issue
Block a user