亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用Javascript檢索二進制文件內容,對base64進行編碼,然后使用Python對其進行反解

使用Javascript檢索二進制文件內容,對base64進行編碼,然后使用Python對其進行反解

慕無忌1623718 2019-11-11 14:24:37
我正在嘗試使用XMLHttpRequest(使用最新的Webkit)下載二進制文件,并使用此簡單功能對base64的內容進行編碼:function getBinary(file){    var xhr = new XMLHttpRequest();      xhr.open("GET", file, false);      xhr.overrideMimeType("text/plain; charset=x-user-defined");      xhr.send(null);    return xhr.responseText;}function base64encode(binary) {    return btoa(unescape(encodeURIComponent(binary)));}var binary = getBinary('http://some.tld/sample.pdf');var base64encoded = base64encode(binary);附帶說明一下,以上所有內容都是標準Javascript內容,包括btoa()和encodeURIComponent():https : //developer.mozilla.org/en/DOM/window.btoa這工作非常順利,我什至可以使用Javascript解碼base64內容:function base64decode(base64) {    return decodeURIComponent(escape(atob(base64)));}var decodedBinary = base64decode(base64encoded);decodedBinary === binary // true現在,我想使用Python解碼base64編碼的內容,該內容使用一些JSON字符串來獲取base64encoded字符串值。天真的,這就是我的工作:import urllibimport base64# ... retrieving of base64 encoded string through JSONbase64 = "77+9UE5HDQ……………oaCgA="source_contents = urllib.unquote(base64.b64decode(base64))destination_file = open(destination, 'wb')destination_file.write(source_contents)destination_file.close()但是生成的文件無效,看起來該操作已被UTF-8,編碼或其他尚不清楚的東西弄亂了。如果在將UTF-8內容放入目標文件之前嘗試對其進行解碼,則會引發錯誤:import urllibimport base64# ... retrieving of base64 encoded string through JSONbase64 = "77+9UE5HDQ……………oaCgA="source_contents = urllib.unquote(base64.b64decode(base64)).decode('utf-8')destination_file = open(destination, 'wb')destination_file.write(source_contents)destination_file.close()$ python test.py// ...UnicodeEncodeError: 'ascii' codec can't encode character u'\ufffd' in position 0: ordinal not in range(128)附帶說明一下,這是同一文件的兩種文本表示形式的屏幕截圖;左:原件;右:從base64解碼的字符串創建的一個:http://cl.ly/0U3G34110z3c132O2e2x嘗試重新創建文件時,是否存在已知的技巧來規避編碼方面的這些問題?您將如何實現自己?任何幫助或暗示非常感謝:)
查看完整描述

2 回答

  • 2 回答
  • 0 關注
  • 643 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號