How to use the get of ajax in js to obtain a file stream from the background for file download (where the token parameter is passed in header)

how to use ajax"s get in js to get a file stream from the background for file save as download

where header needs to pass token and os parameters to the background for verification

how should I write this JS? I hope the great god will not hesitate to give us some advice, thank you ~

the header parameter cannot be obtained in the background with the following method, and the saved window is not launched in the browser

var url = "{-sharp$apiHost-sharp}/aw/export?brand_ids="+brand_ids;
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.setRequestHeader("token", "5f963175cc75613398e25ce2e5da56d7");
xhr.setRequestHeader("os", "1");
xhr.onload = function() {
    if (this.status == 200) {
        try{
            var elemIF = document.createElement("iframe");
            elemIF.src = this.responseURL;
            elemIF.style.display = "none";
            document.body.appendChild(elemIF);
        }catch(e){
        }
    }
}
xhr.send();
Mar.29,2021

I wish I could change it like this.

var xhh = new XMLHttpRequest();
                xhh.open("post", Action.FILES_W_DOWNLOADFILE + "/"+ fileName );
                xhh.setRequestHeader("Authorization", this.Axios.defaults.headers.Authorization = JSON.parse(getCookie('userInfo')).tokenType+ ' ' + JSON.parse(getCookie('userInfo')).accessToken);
                xhh.setRequestHeader("Content-Type","application/json");
                xhh.responseType = 'blob';
                xhh.onreadystatechange = function () {
                    if (xhh.readyState === 4 && xhh.status === 200) {
                        var name = xhh.getResponseHeader("ajax-filename");
                        var mimeType = xhh.getResponseHeader("ajax-mimeType");
                        var blob = new Blob([xhh.response], {type: mimeType});
                        var csvUrl = URL.createObjectURL(blob);
                        var link = document.createElement('a');
                        document.body.appendChild(link); //bodyFirefox
                        link.href = csvUrl;
                        link.target = '_blank';
                        link.id = 'linkId',
                        link.className = 'linkId',
                        link.download = decodeURI(name);
                        document.getElementById("linkId").click();
                        // link.remove(); //a
                        $('.linkId').remove()
                    }
                };
                xhh.send();

in the browser environment, JS does not have the ability to read and write local files. Therefore, if possible, let the background get information such as token from the parameters of GET, and then return the file stream. The front end only needs to use the a tag and the download attribute to download.

< hr >

if you have to read the file stream from the front end and download it, you can use the blob object. However, compatibility is not guaranteed, and blob objects are only available in IE11.

in addition, the failure to receive header at the backend may be caused by a cross-domain problem. As long as it is a cross-domain request with a custom header, the OPTIONS request will be sent before sending the real request. The browser will decide whether to continue to send the real request for cross-domain resource access based on the result returned by the OPTIONS request.

function export_raw(name, blob) {
    // name=, blob=
    var urlObject = window.URL || window.webkitURL || window;
    var save_link = document.createElementNS("http://www.w3.org/1999/xhtml", "a")
    save_link.href = urlObject.createObjectURL(blob);
    save_link.download = name;
    fake_click(save_link);
}

function fake_click(obj) {
    var ev = document.createEvent("MouseEvents");
    ev.initMouseEvent(
        "click", true, false, window, 0, 0, 0, 0, 0
        , false, false, false, false, 0, null
    );
    obj.dispatchEvent(ev);
}

after consulting materials on the Internet, header was successfully sent to the background.
the problem now is that the background has returned the file stream to me. How to use JS to automatically download the returned file stream

var settings = {
  "async": true,
  "crossDomain": true,
  "url": "{-sharp$apiHost-sharp}/aw/export?brand_ids="+brand_ids,
  "method": "GET",
  "headers": {"token": "5f963175cc75613398e25ce2e5da56d7","os": "1"}
}
$.ajax(settings).done(function (data) {
    console.log(data);
});

the above data is the returned file stream. How to use JS correctly to make the returned file stream download automatically?

Menu