2016-09-04 39 views
2

我一直在嘗試通過使用python的API上傳文件到backblaze。上傳圖像到backblaze通過使用python的API

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

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訪問文件。

但是當我試圖通過修改代碼如下面給出上傳圖片下面

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) 

給出(所有其它部件與上述代碼相同)

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

它產生一個錯誤它工作得很好,當我base64編碼的圖像內容,但圖像不能通過公共鏈接訪問。還有其他的方法可以克服嗎?

+0

嘗試使用的編解碼器庫。 'import codecs',然後使用codecs.open('test.jpg','rb',encoding ='utf-8')將open('test.jpg','rb')as..'改爲''。 ' – n1c9

+0

@ n1c9當我嘗試它得到另一個錯誤,因爲UnicodeDecodeError:'utf8'編解碼器無法解碼位置0字節0xff:無效的開始字節' – midhun

回答

0

我只是解決了這個利用requests

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