aiohttp 服务器文件上传:request.post UnicodeDecodeError



>我在Flask中有一个Web服务,可以处理上传的二进制数据:

@app.route('/v1/something', methods=['POST'])
def v1_something():
for name in request.files:
file = request.files[name]
file.read()
...

现在我正在将其重写为 AIOHTTP,但在文件处理方面遇到了一些问题。我的代码:

@routes.post('/v1/something')
async def v1_something(request):
files = await request.post()
for name in files:
file = files[name]
file.read()
...

我在第await request.post()行收到错误:

UnicodeDecodeError:"utf-8"编解码器无法解码位置 14 中的字节0x80:无效的起始字节

看起来 AIOHTTP 尝试将给定的二进制文件读取为文本。我该如何防止这种情况?

我决定阅读源代码,发现request.post()用于application/x-www-form-urlencodedmultipart/form-data,这就是为什么它总是尝试将给定的数据解析为文本。我还发现我应该使用request.multipart()

@routes.post('/v1/something')
async def v1_something(request):
async for obj in (await request.multipart()):
# obj is an instance of aiohttp.multipart.BodyPartReader
if obj.filename is not None:  # to pass non-files
file = BytesIO(await obj.read())
...

最新更新