简体   繁体   English

使用 urllib3 UnicodeDecodeError 上传文件

[英]file upload using urllib3 UnicodeDecodeError

I'm trying to upload a file via a multipart form POST request using urllib3.我正在尝试使用 urllib3 通过多部分表单 POST 请求上传文件。 I followed this example from the urllib docs :我从urllib 文档中遵循了这个例子:

>>> with open('example.txt') as fp:
...     file_data = fp.read()
>>> r = http.request(
...     'POST',
...     'http://httpbin.org/post',
...     fields={
...         'filefield': ('example.txt', file_data),
...     })
>>> json.loads(r.data.decode('utf-8'))['files']
{'filefield': '...'}

When I adapted the example code, I added some extra fields required by the API I'm uploading to:当我修改示例代码时,我添加了一些我上传到的 API 所需的额外字段:

import urllib3

http = urllib3.PoolManager()

with open('/Volumes/GoogleDrive/My Drive/Code/Fuse-Qu/qu/uploads/risk.pdf') as fp:
    file_data = fp.read()

r = http.request(
    'POST',
    'https://***.fuseuniversal.com/api/v4.2/contents/media?auth_token=***',
    fields={
        "name": "test api upload 11",
        "description": "this is a test of uploading a pdf via the api",
        "composite_attributes[type]": "File",
        "community_ids": "24827",
        "composite_attributes[file]": ('risk.pdf', file_data, 'document/pdf'),
    })

However I end up getting this error:但是我最终得到这个错误:

Traceback (most recent call last):
  File "test-urllib.py", line 6, in <module>
    file_data = fp.read()
  File "/Users/dunc/.pyenv/versions/3.8.1/lib/python3.8/codecs.py", line 322, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe2 in position 10: invalid continuation byte

You need to open the file in binary mode because it's not text.您需要以二进制模式打开文件,因为它不是文本。 If you open the file without specifying binary, python3 automatically tries to decode the contents as utf-8.如果您在未指定二进制文件的情况下打开文件,python3 会自动尝试将内容解码为 utf-8。 Here is the failing lines updated:这是更新的失败行:

with open('/Volumes/GoogleDrive/My Drive/Code/Fuse-Qu/qu/uploads/risk.pdf', 'rb') as fp:
    file_data = fp.read()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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