Python 使用urllib3 UnicodeDecodeError上载文件

Python 使用urllib3 UnicodeDecodeError上载文件,python,urllib,urllib3,Python,Urllib,Urllib3,我正在尝试使用urllib3通过多部分表单POST请求上传文件。我从以下方面遵循了这个示例: 当我修改示例代码时,我添加了我要上传到的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.requ

我正在尝试使用urllib3通过多部分表单POST请求上传文件。我从以下方面遵循了这个示例:

当我修改示例代码时,我添加了我要上传到的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'),
    })
但是,我最终得到了以下错误:

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
回溯(最近一次呼叫最后一次):
文件“test urllib.py”,第6行,在
file_data=fp.read()
文件“/Users/dunc/.pyenv/versions/3.8.1/lib/python3.8/codecs.py”,第322行,在decode中
(结果,消耗)=自身缓冲区解码(数据,自身错误,最终)
UnicodeDecodeError:“utf-8”编解码器无法解码位置10中的字节0xe2:无效的连续字节

您需要以二进制模式打开文件,因为它不是文本。如果您在不指定二进制的情况下打开文件,python3会自动尝试将内容解码为utf-8。以下是更新的失败行:

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