How to set request headers before loading in iframe

I need to upload a file with the Content-Disposition header , which is set by the server to " attachment". I use jQuery.ajaxfor GET, and when deleting - hidden iframe src- urlwhich gives me a pop-up window for downloading the file. And it works fine in all browsers. Now I want to change my own request headers to encrypt the file before GET and download. For this, I used jQuery.ajaxthe request callback function beforeSend.

I can get my encrypted file, which I can watch in firebug, but mine iframestill shows an unencrypted file to load. After checking, I can say that it is iframerequesting a new GET.

the code

$.ajax({
url: "/tutorial.text",
beforeSend: function(xhr) {  xhr.setRequestHeader("PASSWORD_HEADER", userPwd);  },
success: function() {   $("#Hidden_iframe").attr("src", this.url);  }                                   
});

And it works well in Internet Explorer. How can I make an iframe use an available resource, rather than request a new GET. Or how can I setRequestHeader in an iframe, or do I really need jQuery.ajaxfor this task, is there a better way to load the Content-Disposition header, which is installed in the attachment files directly from the server.

+5
source share
1 answer

This solution does not use an iframe or form. It uses XHR with a custom header on a resource that supports CORS (just random svg from the Internet for this example). The key differences in this approach are the xhr.responseType = 'arraybuffer';relationship with the blobhref and attributes 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');
});
Run codeHide result

Tested on Chrome57 and FF54.

0

All Articles