文件下載的功能可以借助第三方插件,也可以通過穿件a標簽的方式進行文件下載,下面就介紹一下通過a鏈接的方式下載文件
接口 配置:
export const downloadDescription = (params) => { return request({ method: 'GET', responseType: "blob", // 這行配置可不能少 url: "/price_portal/file-upload/downloadDescription", params }) }
在使用的頁面導入接口
import * as Api from "@/xxx"; // 接口所在的文件地址
在vue頁面中使用接口
async handleDown() { let res = await Api.downloadDescription( // 參數 { fileName: "" }, // 請求頭 { headers: { "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8", }, } ); if (res.request.status == 200) { let blob = new Blob([res.data], { type: "application/msword", });
// application/msword為word類型文檔 new Blob 中的type類型可在下面的截圖中查看 let fileName = "數據接口使用說明";
if (window.navigator && window.navigator.msSaveOrOpenBlob) { // IE window.navigator.msSaveOrOpenBlob(blob, fileName); } else { let objectUrl = (window.URL || window.webkitURL).createObjectURL( blob ); let downFile = document.createElement("a"); downFile.style.display = "none"; downFile.href = objectUrl; downFile.download = fileName; // 下載后文件名 document.body.appendChild(downFile); downFile.click(); document.body.removeChild(downFile); // 下載完成移除元素 // window.location.href = objectUrl window.URL.revokeObjectURL(objectUrl); // 只要映射存在,Blob就不能進行垃圾回收,因此一旦不再需要引用,就必須小心撤銷URL,釋放掉blob對象。 } } },
除了上述用到的方法還可以借助下面的第三方插件實現下載的功能
downloadjs // npm install downloadjs 使用教程參考鏈接
js-file-download //npm install js-file-download 使用教程參考鏈接

