我正在尝试使用最新的Webkit和XMLHttpRequest
下载二进制文件,并使用这个简单的函数对其内容进行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 urllib
import base64
# ... retrieving of base64 encoded string through JSON
base64 = "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 urllib
import base64
# ... retrieving of base64 encoded string through JSON
base64 = "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 在尝试重新创建文件时,有没有已知的技巧可以避免这些编码问题?您将如何实现这一点?
任何帮助或提示都会受到高度赞赏 :)
base64encode()
еҮҪж•°ж— жі•иҪ¬жҚўжҹҗдәӣеӯ—з¬Ұ...еҘҮжҖӘзҡ„жҳҜпјҢеҸҚеҗ‘ж“ҚдҪңеңЁjavascriptдёӯе®ҢзҫҺиҝҗиЎҢ... - NiKobtoa()
、encodeURIComponent()
和unescape()
)是标准的。Python部分也是如此,除了stdlib之外没有其他东西被使用...我将研究一下奇怪的字节值,但这看起来会非常麻烦:( - NiKo