使用 FastAPI 和 Boto3 将 PDF 上传到 AWS S3 时出现问题

问题描述 投票:0回答:1

我在尝试使用 FastAPI 和 boto3 库将 PDF 文件上传到 AWS S3 存储桶时遇到问题。文件似乎上传成功,但从 S3 下载相同的 PDF 时,它们显示完全空白。无法从下面的代码中理解问题出在哪里。


@router.post('/upload', tags=["Upload Files"])
async def upload_file(
        Type: str = Form(...),
        Id: str = Form(None),
        dept: str = Form(...),
        PolicyType=Form(...),
        file: UploadFile = File(...),
        userId: str = Depends(get_current_user)
):

    fileObj, fileName = validate_post_request(file)
    content = await file.read()
    
    

    filePath = f"{Type}/{Id}/{uniqueId}"

    # Store data in S3
    fileObj.seek(0)
    s3Response = upload_to_s3(content,S3_BUCKET_NAME, filePath)
    if not s3Response:
        logger.error('Unable to upload file')
        raise HTTPException(status_code=500, detail="Unable to upload file, try again later")

    response = {
        'error': False,
        'message': 'Uploaded successfully',
    }
    return response



def upload_to_s3(file_obj: bytes, bucket: str, object_name: str) -> bool:
    try:
        s3_client.put_object(
            Bucket=bucket,
            Key=object_name,
            Body=file_obj
        )
    except Exception as err:
        return False
    return True


我尝试生成预签名 URL,然后将 pdf 文件附加到其中,但结果相同,在 s3 上完全空白

python-3.x amazon-s3 boto3 fastapi
1个回答
0
投票

我不太确定你的代码有什么问题,但我做了这样的事情

@app.post("/upload/")
async def upload_file(file: UploadFile):
    s3 = boto3.client('s3')
    s3.upload_fileobj(file.file, bucket_name, file_name)
© www.soinside.com 2019 - 2024. All rights reserved.