use*_*751 5 iframe jquery http-headers
我需要下载一个文件,其中' Content-Disposition '标题attachment由服务器设置为" ".我使用 jQuery.ajax了GET和成功设置隐藏iframe src到url,这给了我一个弹出的文件下载.它在所有浏览器中都运行良好.现在我想在GET和下载之前更改自定义请求标头以加密文件.我使用了 jQuery.ajax预请求回调函数beforeSend.
我能够获取我可以在firebug中观察到的加密文件,但我iframe仍然显示非加密文件供下载.检查后我可以说iframe要求新的GET.
码
$.ajax({
url: "/tutorial.text",
beforeSend: function(xhr) { xhr.setRequestHeader("PASSWORD_HEADER", userPwd); },
success: function() { $("#Hidden_iframe").attr("src", this.url); }
});
Run Code Online (Sandbox Code Playgroud)
这在Internet Explorer上运行良好.我如何强制iframe使用可用资源而不是请求新的GET.或者我如何在iframe中设置setRequestHeader或者我是否真的需要jQuery.Ajax这个任务是否有任何最好的方法来下载直接从服务器设置为附件文件的Content-Disposition标头.
此解决方案不使用 iframe 或表单。它在支持 CORS 的资源上使用带有自定义标头的 XHR(本例中只是来自互联网的随机 svg)。这种方法的主要区别是带有href 和属性xhr.responseType = 'arraybuffer';的链接:blobdownload
// some initial data
var url = '//enable-cors.org/img/cloud-download.svg';
var password = '123456';
// download url into arrayBuffer
function download (url, password, cb) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'arraybuffer';
// xhr.setRequestHeader('PASSWORD_HEADER', password);
xhr.onload = function () {
cb(xhr.response);
};
xhr.send(null);
}
// receive binary content of url
// create blob link and click on it
download(url, password, function (arrayBuffer) {
var file = new File([arrayBuffer], 'some filename');
var a = document.createElement('A');
a.setAttribute('href', window.URL.createObjectURL(file));
a.setAttribute('download', 'file-name-of-download.ext');
// in firefox `a.click()` works only if `a` element is in DOM, so...
document.documentElement.appendChild(a);
a.click();
console.log('done');
});Run Code Online (Sandbox Code Playgroud)
在 Chrome57 和 FF54 中测试。
| 归档时间: |
|
| 查看次数: |
4783 次 |
| 最近记录: |