1. 程式人生 > 實用技巧 >vue檔案下載功能

vue檔案下載功能

vue檔案下載功能

第一種

html

js
  window.open(`${this.$config.IPUPLOAD}file/${id}`, "hidden_frame");


第二種

   html 
    下載
      
js 

 toDownLoad(id) {
      if (!this.isDownLoadNow) {
        this.isDownLoadNow = true;
        this.$getRequest(`${this.$config.IPUPLOAD}file/${id}/presignedurl`)
          .then(res 
=> { console.log("檔案下載", res); this.downloadhttp = res.presignedUrl; // this.isDownLoadNow = false; setTimeout(() => { this.$refs.downLoadA.click(); this.isDownLoadNow = false; }, 1000); // let a = document.createElement("button");
// a.href = res.presignedUrl; // a.click(); }) .catch(() => { this.$message.error("請求檔案失敗", 1); }); } }, 經過試驗正確的方法 xtract(scope) { axios({ // 用axios傳送post請求 method: "post", url: `${this.$config.MONSTA}/groupService/downFile?id=` + scope.row.id, //
請求地址 // 引數 responseType: "blob", // 表明返回伺服器返回的資料型別 headers: { "Content-Type": "application/json" } }).then(res => { // 處理返回的檔案流 const blob = new Blob([res.data]); //new Blob([res])中不加data就會返回下圖中[objece objece]內容(少取一層) const fileName = "統計.xlsx"; //下載檔名稱 const elink = document.createElement("a"); elink.download = fileName; elink.style.display = "none"; elink.href = URL.createObjectURL(blob); document.body.appendChild(elink); elink.click(); URL.revokeObjectURL(elink.href); // 釋放URL 物件 document.body.removeChild(elink); }); }, 另一篇文章:https://blog.csdn.net/weixin_43216105/article/details/105998242?utm_medium=distribute.pc_category.none-task-blog-hot-4.nonecase&depth_1-utm_source=distribute.pc_category.none-task-blog-hot-4.nonecase&request_id= 第一種方式是前端建立超連結,通過a標籤的連結向後端服務發get請求,接收後端的檔案流,非常簡單: 下載模板 另一種情況是建立div標籤,動態建立a標籤: 下載 function downloadExcel() { let a = document.createElement('a') a.href ="/user/downloadExcel" a.click(); } 第二種方式通過建立iframe的方式: 匯出 //method方法: handleExport(row) { var elemIF = document.createElement('iframe') elemIF.src = 'user/downloadExcel?snapshotTime=' + formatDate(new Date(row.snapshotTime), 'yyyy-MM-dd hh:mm') + '&category=' + row.category elemIF.style.display = 'none' document.body.appendChild(elemIF) } 第三種方式,會對後端發的post請求,使用blob格式 匯出 //method方法 handleExport(row){ const url="/user/downloadExcel" const options = {snapshotTime:formatDate(new Date(row.snapshotTime), 'yyyy-MM-dd hh:mm')} exportExcel(url,options) } /** * 封裝匯出Excal檔案請求 * @param url * @param data * @returns {Promise} */ //api.js export function exportExcel(url, options = {}) { return new Promise((resolve, reject) => { console.log(`${url} 請求資料,引數=>`, JSON.stringify(options)) axios.defaults.headers['content-type'] = 'application/json;charset=UTF-8' axios({ method: 'post', url: url, // 請求地址 data: options, // 引數 responseType: 'blob' // 表明返回伺服器返回的資料型別 }).then( response => { resolve(response.data) let blob = new Blob([response.data], { type: 'application/vnd.ms-excel' }) console.log(blob) let fileName = Date.parse(new Date()) + '.xlsx' if (window.navigator.msSaveOrOpenBlob) { // console.log(2) navigator.msSaveBlob(blob, fileName) } else { // console.log(3) var link = document.createElement('a') link.href = window.URL.createObjectURL(blob) link.download = fileName link.click() //釋放記憶體 window.URL.revokeObjectURL(link.href) } }, err => { reject(err) } ) }) } 實現功能具體程式碼 let data = res; if (!data) { this.$message.error("下載失敗,解析資料為空!"); return; } const datetime = Date.now(); // 建立一個新的url,此url指向新建的Blob物件 let url = window.URL.createObjectURL(new Blob([data])); // 建立a標籤,並隱藏改a標籤 let link = document.createElement("a"); link.style.display = "none"; // a標籤的href屬性指定下載連結 link.href = url; //setAttribute() 方法新增指定的屬性,併為其賦指定的值。 let fileName = datetime + "." + this.downType; link.setAttribute("download", fileName); document.body.appendChild(link); link.click(); this.$message.success("匯出成功");