使用POST下載文件

一直以來,JS都沒有比較好的能夠直接處理二進制的方法。而Blob的存在,容許咱們能夠經過JS直接操做二進制數據。
1、下載
util.fetchDownload= function (opt,data) { return fetch(opt.url,{ method: "POST", headers: { 'Content-Type': 'application/json', }, mode: "cors", body: JSON.stringify(data), credentials: 'include' }).then(resp => resp.blob().then(blob => { const disposition = resp.headers.get("content-disposition"); const match = disposition ? disposition.match(/attachment; filename="(.+)"/i) : null; const filename = match && match.length > 1 ? match[1] : snTime + ".xls"; if (window.navigator.msSaveOrOpenBlob) { navigator.msSaveBlob(blob, filename); //兼容ie10 } else { var a = document.createElement('a'); document.body.appendChild(a) //兼容火狐,將a標籤添加到body當中 var url = window.URL.createObjectURL(blob); // 獲取 blob 本地文件鏈接 (blob 爲純二進制對象,不可以直接保存到磁盤上) a.href = url; a.download = filename; a.target='_blank' // a標籤增長target屬性 a.click(); a.remove() //移除a標籤 window.URL.revokeObjectURL(url); } }).then(function () { opt.success() }))};
相關文章
相關標籤/搜索