使用python通过API上传图像以进行反向启动

时间:2016-09-04 17:20:14

标签: python image api non-ascii-characters

我一直在尝试使用python通过API将文件上传到backblaze。

以下是我使用的代码段。

import json
import urllib2
import hashlib

upload_url = "" # Provided by b2_get_upload_url
upload_authorization_token = "" # Provided by b2_get_upload_url
file_data = "Now, I am become Death, the destroyer of worlds."
file_name = "oppenheimer_says.txt"
content_type = "text/plain"
sha1_of_file_data = hashlib.sha1(file_data).hexdigest()

headers = {
    'Authorization' : upload_authorization_token,
    'X-Bz-File-Name' :  file_name,
    'Content-Type' : content_type,
    'X-Bz-Content-Sha1' : sha1_of_file_data
}
request = urllib2.Request(upload_url, file_data, headers)

response = urllib2.urlopen(request)
response_data = json.loads(response.read())
response.close()

工作正常,可以通过网络用户界面访问文件。

但当我尝试通过修改下面给出的代码上传图像时(所有其他部分与上面的代码相同)

with open('test.jpg', 'rb') as content_file:
    file_data = content_file.read()
file_name = "test.jpg"
content_type = "b2/x-auto"

它会引发错误,如下所示

File "/usr/lib/python2.7/httplib.py", line 848, in _send_output
msg += message_body
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0:      ordinal not in range(128)

当我对base64编码图像内容时,它工作正常,但无法通过公共链接访问图像。还有其他方法可以解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

我刚刚使用requests

解决了这个问题

response = requests.post(upload_url, headers=headers, data=file_data)