我正在嘗試使用XMLHttpRequest(使用最新的Webkit)下載二進(jìn)制文件,并使用此簡(jiǎn)單功能對(duì)base64的內(nèi)容進(jìn)行編碼: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);附帶說(shuō)明一下,以上所有內(nèi)容都是標(biāo)準(zhǔn)Javascript內(nèi)容,包括btoa()和encodeURIComponent():https : //developer.mozilla.org/en/DOM/window.btoa這工作非常順利,我什至可以使用Javascript解碼base64內(nèi)容:function base64decode(base64) { return decodeURIComponent(escape(atob(base64)));}var decodedBinary = base64decode(base64encoded);decodedBinary === binary // true現(xiàn)在,我想使用Python解碼base64編碼的內(nèi)容,該內(nèi)容使用一些JSON字符串來(lái)獲取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()但是生成的文件無(wú)效,看起來(lái)該操作已被UTF-8,編碼或其他尚不清楚的東西弄亂了。如果在將UTF-8內(nèi)容放入目標(biāo)文件之前嘗試對(duì)其進(jìn)行解碼,則會(huì)引發(fā)錯(cuò)誤: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)附帶說(shuō)明一下,這是同一文件的兩種文本表示形式的屏幕截圖;左:原件;右:從base64解碼的字符串創(chuàng)建的一個(gè):http://cl.ly/0U3G34110z3c132O2e2x嘗試重新創(chuàng)建文件時(shí),是否存在已知的技巧來(lái)規(guī)避編碼方面的這些問(wèn)題?您將如何實(shí)現(xiàn)自己?任何幫助或暗示非常感謝:)
使用Javascript檢索二進(jìn)制文件內(nèi)容,對(duì)base64進(jìn)行編碼,然后使用Python對(duì)其進(jìn)行反解
慕無(wú)忌1623718
2019-11-11 14:24:37