首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用python通过API上传图片到backblaze

使用python通过API上传图片到backblaze
EN

Stack Overflow用户
提问于 2016-09-05 01:20:14
回答 1查看 635关注 0票数 2

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

以下是我使用的代码片段。

代码语言:javascript
复制
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访问文件。

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

代码语言:javascript
复制
with open('test.jpg', 'rb') as content_file:
    file_data = content_file.read()
file_name = "test.jpg"
content_type = "b2/x-auto"

它会引发如下所示的错误

代码语言:javascript
复制
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编码时,它工作得很好,但是图像不能通过公共链接访问。有没有其他方法可以克服这个问题?

EN

回答 1

Stack Overflow用户

发布于 2017-11-06 14:24:18

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

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39319544

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档