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

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

我在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尝试读取给定的二进制文件作为文本。我该如何预防?

python aiohttp
1个回答
0
投票

我决定阅读源代码,发现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())
            ...

documentation with an example of request.post()确实令人困惑。

© www.soinside.com 2019 - 2024. All rights reserved.