[英]file upload using urllib3 UnicodeDecodeError
我正在嘗試使用 urllib3 通過多部分表單 POST 請求上傳文件。 我從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': '...'}
當我修改示例代碼時,我添加了一些我上傳到的 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
您需要以二進制模式打開文件,因為它不是文本。 如果您在未指定二進制文件的情況下打開文件,python3 會自動嘗試將內容解碼為 utf-8。 這是更新的失敗行:
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.