The following is a simple operation of JS download file flow that I have compiled for you. Interested students can take a look.
The download code is as follows:
var xhr = new XMLHttpRequest(); var formData = new FormData(); formData.append('snNumber', $("#snNumber").val()); formData.append('spec', $("#spec").val()); formData.append('startCreateDate', $("#startCreateDate").val()); formData.append('endCreateDate', $("#endCreateDate").val()); formData.append('startActiveDate', $("#startActiveDate").val()); formData.append('endActiveDate', $("#endActiveDate").val()); formData.append('supplier', $("#supplier").val()); formData.append('state', $("#cboDeviceStatus").val()); xhr.open('POST', vpms.ajaxUrl + vpms.manageUserUrl + "exportExcelDevices", true); xhr.setRequestHeader("accessToken", userInfo.accessToken); xhr.responseType = 'blob'; xhr.onload = function (e) { if (this.status == 200) { var blob = this.response; var filename = "设备导出{0}.xlsx".format(vpms.core.date.format("yyyyMMddhhmmss")); var a = document.createElement('a'); blob.type = "application/excel"; var url = createObjectURL(blob); a.href = url; a.download = filename; a.click(); window.URL.revokeObjectURL(url); } }; xhr.send(formData); });
The download using Chrome runs well, but the IE Explorer 11 version export Excel button does not respond or pops up "A new application is required to open this blob" .
Improve the blob processing method: as follows
if (window.navigator.msSaveOrOpenBlob) { navigator.msSaveBlob(blob, filename); } else { var a = document.createElement('a'); blob.type = "application/excel"; var url = createObjectURL(blob); a.href = url; a.download = filename; a.click(); window.URL.revokeObjectURL(url); }
At this time, the export under IE is normal:
The above is what I compiled for everyone The simple operation of JS download file stream, I hope it will be helpful to everyone in the future.
Related articles:
About a simple call to obtain JSON data in JS (the code is attached, simple and crude)
How to use JS to submit a request using POST method (detailed answer combined with the code)
The above is the detailed content of Simple operation of JS download file stream (code attached). For more information, please follow other related articles on the PHP Chinese website!