简体   繁体   中英

python 3.5 + aiohttp: TypeError: a bytes-like object is required, not 'str' when use io.BytesIO

example i send file

with open('test_zip'), 'wb') as f:
    f.write(content)
res = requests.post(URL, data={'file': content})

And then I try to get the file on the server side

async def handle(request):
    form = await request.post()
    data = io.BytesIO((form['file']))
    with open('test_zip_2', 'wb') as file:
            file.write(data)

And an error occurs, but I can open a new archive with Ubuntu

data = io.BytesIO((form['file'])) TypeError: a bytes-like object is required, not 'str'

You don't need to convert FileField to io.BytesIO at all.

Use FileField.file.read() to get file content:

async def handle(request):
    form = await request.post()
    with open('test_zip_2', 'wb') as f:
        f.write(form['file'].file.read())

See File Uploads part - aio documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM