Skip to main content
 首页 » 编程设计

jquery之如何在将请求 header 加载到 iframe 中之前设置请求 header

2026年10月07日4oomusou

我需要下载一个文件,其“Content-Disposition” header 被服务器设置为“attachment”。我使用 jQuery.ajax 进行 GET 并成功将隐藏的 iframe src 设置为 url,它会弹出一个文件下载窗口。并且它在所有浏览器中都运行良好。 现在我想更改自定义请求 header 以在获取和下载之前加密文件。我使用了 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);  }                                    
}); 

这在 Internet Explorer 上运行良好。我如何强制 iframe 使用可用资源而不是请求新的 GET。 或者我如何在 iframe 中 setRequestHeader 或者我真的需要 jQuery.Ajax 来完成此任务吗?有没有最好的方法来下载设置为附件文件的 Content-Disposition header 直接从服务器。

请您参考如下方法:

此解决方案不使用 iframe 或表单。它在支持 CORS 的资源上使用带有自定义 header 的 XHR(本例中只是来自互联网的随机 svg)。此方法的主要区别在于 xhr.responseType = 'arraybuffer'; 以及带有 blob href 和 download 属性的链接:

jsfiddle

// 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'); 
});

在 Chrome57 和 FF54 中测试。