This article describes the common methods of JQuery to achieve file download. Share with you for your reference, as follows:
GET method
1 |
|
POST method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
Why can't ajax download files
The data types returned by the server supported by ajax are: xml, json, script, html, and other types (such as binary streams) will be returned as Strings, which cannot trigger the browser's download processing mechanism and programs.
1 2 3 4 5 6 7 |
|
Ajax download file all code
function testAjaxDownload(){
var url = "http://127.0.0.1:8080/candidateData/txtdownload";
$.ajax({
type:'get',
url: url,
async:false,
success:function(data, statusTest, xhr){
console.log(xhr);
console.log(xhr.getAllResponseHeaders());//获取所有的响应头消息
let fileName = xhr.getResponseHeader("content-disposition").split(';')[1].split('=')[1].replace(/\"/g,'')
let type = xhr.getResponseHeader("content-type")
let blob = new Blob([data],{type:type})
//对于<a>标签,只有 Firefox 和 Chrome(内核) 支持 download 属性
//IE10以上支持blob但是依然不支持download
if ('download' in document.createElement('a')) { //支持a标签download的浏览器
const link = document.createElement('a')//创建a标签
link.download = fileName//a标签添加属性
link.style.display = 'none'
link.href = URL.createObjectURL(blob)
document.body.appendChild(link)
link.click()//执行下载
URL.revokeObjectURL(link.href) //释放url
document.body.removeChild(link)//释放标签
} else { //其他浏览器
if(window.navigator.msSaveOrOpenBlob){
window.navigator.msSaveOrOpenBlob(blob,fileName)
}
}
}
});
}
Note: There is no problem with downloading text files in the above method, but there is a problem with downloading binary files such as excel and word files.
HTML5 Blob object
For a long time, JS has not had a better way to deal with binary directly. The existence of Blob allows us to directly manipulate binary data through JS. The Blob object can be seen as a container for storing binary data.
Create Blob object
1 |
|
- dataArr: An array containing the data to be added to the Blob object. The data can be any number of ArrayBuffer, ArrayBufferView, Blob, or DOMString objects.
- opt: object, contains two attributes
- type: used to set the attributes of the Blob object (such as: MIME type)
- endings: (obsolete), set the endings parameter of the BlobBuilder.append() method, the value is "transparent" or "native"
1 2 3 4 |
|
xmlhttprequest 2 + Blob to achieve file download
The xmlhttprequest 2 standard supports streaming files, used xhr.response
as a return (not responseText)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
Note: Use xmlhttprequest to specifyresponseTyp为blob,但是使用ajax是不能指定responseType为blob的