【问题标题】:FastAPI fileupload to S3FastAPI 文件上传到 S3
【发布时间】:2021-10-20 01:13:35
【问题描述】:

我正在编写一个 FastAPI 端点来将文件上传到 S3 对象存储。以下是代码sn-p。但是,我得到一个异常 "expected string or bytes-like object"

我不想暂时保存文件然后上传。

我在 FastAPI 文档中读到,UploadFile 具有文件属性,它是一个 “实际的 Python 文件 (SpooledTemporaryFile),您可以将其直接传递给其他需要“类文件”对象的函数或库”。由于 boto3 的 upload_fileobj 函数需要一个字符串或类似字节的参数,因此我使用 SpooledTemporaryFile 的 _file 属性将类似文件的对象转换为 BytesIO 对象。但是还是报错“expected string or bytes-like object”

任何指针将不胜感激。

@app.post("/uploadFile")
async def upload_file(fileobject: UploadFile = File(...),filename: str = Body(default=None),key: str = Body(default=None),):
extension = fileobject.filename.rsplit(".", 1)[1].lower()
if key is None:
    raise HTTPException(status_code=400, MissingError="Key is missing")
if filename is None:
    filename = fileobject.filename
if fileobject.filename.endswith(tuple(ALLOWED_EXTENSIONS)):    
    data = (
        fileobject.file._file
    )  # Using _file attribute convert tempfile.SpooledTemporaryFile to io.BytesIO
    try:
        # Upload the file to Spaces
        upload_result = await client.upload_fileobj(
            data,
            BUCKET,
            f"{key}/{filename}",
            ExtraArgs={
                "ACL": "public",
                "ContentType": FILE_CONTENT_TYPES[extension],
            },
        )
        if upload_result:
            object_url = f"{OBJ_URL}/{key}/{file.filename}"
            doc = [{"file_url": object_url}]
        else:
            raise HTTPException(status_code=400, detail="Failed to upload in S3")
    except Exception as e:
        logging.error(f"Exception while uploading file - {e}")
        raise HTTPException(
            status_code=400, detail=f"Exception {e} while uploading the file"
        )
else:
    raise HTTPException(
        status_code=400, detail=f"File of type {extension} is not allowed"
    )

【问题讨论】:

    标签: python python-3.x amazon-s3


    【解决方案1】:

    我有一个类似的问题,但问题是存储桶名称,我的是 None/empty,错误消息很烦人,存储桶应该是一个非空字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-19
      • 1970-01-01
      • 2020-11-12
      • 2021-11-28
      • 1970-01-01
      • 2011-12-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多