我正在尝试使用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);
Run Code Online (Sandbox Code Playgroud)
作为旁注,上面的所有内容都是标准的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
Run Code Online (Sandbox Code Playgroud)
现在,我想使用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 …Run Code Online (Sandbox Code Playgroud) 假设我有这样的代码:
<img src='images/whatever.jpj' width='' height=''/>
Run Code Online (Sandbox Code Playgroud)
如何为此请求配置自定义标头?
将不胜感激任何帮助