Article reference
http://blog.csdn.net/zhoumengshun/article/details/71405963
https://segmentfault.com/q/1010000011184241
Encountered the following problems at work:
To download a file through the gateway, the gateway must bring a token value placed in the header request header. If there is no token, it will be directly intercepted, and the request will not go to the service that actually handles the business logic.
question:
1. If you want to put the token parameter in the header, you can only use ajax .
2. If you use ajax, you can only get the read-only data returned , and cannot write it to the hard disk as a file
Solution:
Put the token as a parameter in the URL after hello, for example: http://www.baidu.com?token=dsadfasfdsaf
The following four ways are my summary of the method of separating the downloaded files from the front and back ends
a. form download file
//Download the file directly in the form //url indicates the file path to download, such as: http://127.0.0.1/test.rar function downloadFile(url){ var form=$("<form>");//Define the form form and send the request through the form form.attr("style","display:none");//Set to not display form.attr("target",""); form.attr("method","get");//Set the request type form.attr("action",url);//Set the request path $("body").append(form);//Add the form to the page (body) form.submit();//Form submission }
b. iframe download file
function downloadFile(url) { try{ var elemIF = document.createElement("iframe"); elemIF.src = url; elemIF.style.display = "none"; document.body.appendChild(elemIF); }catch(e){ } }
c. Link to download file
<a href=”file.js”>file.js</a> //This method is not supported by some versions of Firefox window.location.href="htpp://www.baidu.com/test.rar" //In order to solve the problem that some versions of Firefox do not support, you can change it to this way window.location="htpp://www.baidu.com/test.rar"; //This method has no effect on Firefox, but it is ok on IE browser window.open("htpp://www.baidu.com/test.rar")
d. Ajax can only get text data (if the data stream has been converted to Blob, base64 format)
function saveFile(url) { return new Promise(function(resolve, reject) { // Get file name from url. var filename = url.substring(url.lastIndexOf("/") + 1).split("?")[0]; var xhr = new XMLHttpRequest(); xhr.responseType = 'blob'; xhr.onload = function() { resolve(xhr); }; xhr.onerror = reject; xhr.open('GET', url); xhr.send(); }).then(function(xhr) { var a = document.createElement('a'); a.href = window.URL.createObjectURL(xhr.response); // xhr.response is a blob a.download = filename; // Set the file name. a.style.display = 'none'; document.body.appendChild(a); a.click(); return xhr; }); }
Note: the responseType of the ajax request is "blob", here is the data of the file returned after the request is sent