【问题标题】:How to set Request Headers before it being loaded in an iframe如何在将请求标头加载到 iframe 之前设置请求标头
【发布时间】:2012-06-09 06:18:26
【问题描述】:

我需要下载一个文件,该文件的“Content-Disposition”标头被服务器设置为“attachment”。我将jQuery.ajax 用于GET 并成功设置隐藏iframe srcurl,这给了我一个文件下载的弹出窗口。它在所有浏览器中都能正常工作。 现在我想在 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);  }                                   
});

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

【问题讨论】:

  • 你有没有得到这个答案?我正在尝试做类似的事情...通过ajax调用下载文件,但下载需要身份验证并且它是跨域的......

标签: jquery iframe http-headers


【解决方案1】:

此解决方案不使用 iframe 或表单。它在支持 CORS 的资源上使用带有自定义标头的 XHR(此示例中只是来自 Internet 的随机 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 中测试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-14
    • 2012-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-30
    • 2020-10-09
    • 1970-01-01
    相关资源
    最近更新 更多