PDF 的大小使用 python-multipart 破坏了 FastAPI?

Size of PDF breaks FastAPI using python-multipart?

我正在尝试将 PDF 上传到 FastAPI。将 PDF 转换为 base64-blob 并将其存储在 txt 文件中后,我 POST 使用 Postman 将该文件发送到 FastAPI。

这是我的服务器端代码:

from fastapi import FastAPI, File, UploadFile
import base64

app = FastAPI()

@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
    contents = await file.read()
    blob = base64.b64decode(contents)
    pdf = open('result.pdf','wb')
    pdf.write(blob)
    pdf.close()
    return {"filename": file.filename}

此过程适用于大小为 279KB(blob 大小:372KB)的单页 PDF 文档,但不适用于大小为 1.8MB(blob 大小:2.4MB)的多页文档.

当我尝试时,我收到以下警告和 400 错误请求响应(以及响应 "detail":"There was an error parsing the body"): "Did not find boundary character 55 at index 2"

我确定必须对此行为进行解释?也许它与异步有关?

这很可能是使用 open() 保存文件的问题。

对于大文件 pdf.close() 将在 pdf.write() 完成保存文件的所有内容之前执行。

为了保证整个文件在关闭前都被写入,使用with比如这样:

with open('failed.pdf', 'wb') as outfile:
    outfile.write(blob)

使用 with 后,您将不需要 close()with 也应被视为将文件保存到局部变量中的最佳实践。