前端下載文件大概有以下種: 1)a標簽鏈接下載 2)表單form提交下載 3)使用XMLHttpRequest對象下載 ...
前端下載文件大概有以下種:
1)a標簽鏈接下載
<a href="url">點擊鏈接下載</a>
2)表單form提交下載
var form = $("<form></form>").attr("action", url).attr("method", "post"); form.append($("<input></input>").attr("type", "hidden").attr("name", "參數1").attr("value", "值1")); form.append($("<input></input>").attr("type", "hidden").attr("name", "參數2").attr("value", "值2")); form.appendTo('body').submit().remove();
//url為請求地址
3)使用XMLHttpRequest對象下載
var xhr = new XMLHttpRequest(); var formData = new FormData(); formData.append('參數1', "值1"); formData.append('參數2',"值2"); xhr.open('POST', url, true); xhr.setRequestHeader("token", token); //可以帶請求頭 xhr.responseType = 'blob'; xhr.onload = function (e) { if (this.status == 200) { var blob = this.response; //var responseHeaders = xhr.getAllResponseHeaders(); //var ContentDisposition = this.getResponseHeader("Content-Disposition"); //var filename = this.getResponseHeader("Content-Disposition").split('filename=')[1];
// 獲取文件名,需要在後端響應頭暴露("Access-Control-Expose-Headers", "Content-Disposition");
var filename = "xxxx.xxx"; if (window.navigator.msSaveOrOpenBlob) { navigator.msSaveBlob(blob, filename); } else { blob.type = "application/octet-stream"; var url = URL.createObjectURL(blob); var a = document.createElement('a'); a.href = url; a.download = filename; a.click(); window.URL.revokeObjectURL(url); } }else if(this.status == 404){ alert("file does not exist!"); }else{ alert("failed to download file! "); } }; xhr.send(formData);