Skip to main content
 首页 » 编程设计

python之使用 python 通过 API 将图像上传到 backblaze

2025年04月02日10kenshinobiy

我一直在尝试使用 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() 

它工作正常并且能够通过 Web UI 访问文件。

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

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 编码时它工作正常,但无法通过公共(public)链接访问该图像。有没有其他方法可以克服这个问题?

请您参考如下方法:

我刚刚使用 requests 解决了这个问题,

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