我對 FastAPI 很陌生。我想驗證上傳檔案的檔案型別和檔案大小,Exception如果它超過大小并且與型別不匹配,則提出。這個檔案將被上傳到S3
這就是我的代碼的樣子
@router.post("/upload/", status_code=200, description="***** Upload customer document asset to S3 *****")
async def upload(
document_type: DocumentEnum,
customer_id: UUID,
current_user=Depends(get_current_user),
fileobject: UploadFile = File(...)
):
# delete the file from memory and rollover to disk to save unnecessary memory space
fileobject.file.rollover()
fileobject.file.flush()
valid_types = [
'image/png',
'image/jpeg',
'image/bmp',
'application/pdf'
]
await validate_file(fileobject, 5000000, valid_types)
# .... Proceed to upload file
我的validate_file功能看起來像這樣
async def validate_file(file: UploadFile, max_size: int = None, mime_types: list = None):
"""
Validate a file by checking the size and mime types a.k.a file types
"""
if mime_types and file.content_type not in mime_types:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="You can only upload pdf and image for document"
)
if max_size:
size = await file.read()
if len(size) > max_size:
raise HTTPException(
status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,
detail="File size is too big. Limit is 5mb"
)
return file
現在,當檔案上傳到 時S3,它總是0 bytes大小。但是,如果我從函式中排除檔案大小檢查validate_file,那么原始檔案會被上傳并且沒有問題。如果validate_file函式是這樣的,那么它可以正常上傳
async def validate_file(file: UploadFile, max_size: int = None, mime_types: list = None):
"""
Validate a file by checking the size and mime types a.k.a file types
"""
if mime_types and file.content_type not in mime_types:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="You can only upload pdf and image for document"
)
)
return file
我不知道為什么會這樣。預先感謝您的幫助。
uj5u.com熱心網友回復:
當您呼叫read檔案時,當前檔案指標將位于您讀取的內容的末尾。當您(或庫)read第二次呼叫時,內部檔案指標將已經位于檔案末尾。
您可以使用await file.seek(0)將檔案指標放在檔案的開頭,以便下一次讀取將再次讀取相同的內容:
if max_size:
size = await file.read()
if len(size) > max_size:
raise HTTPException(
status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,
detail="File size is too big. Limit is 5mb"
)
await file.seek(0)
return file
您可能還想顯式決議檔案的 mime 型別,而不是相信用戶所說的檔案是什么 - 您可以使用mimetypes.guess_type或類似的東西來做到這一點。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/434209.html
