文件下载的功能可以借助第三方插件,也可以通过穿件a标签的方式进行文件下载,下面就介绍一下通过a链接的方式下载文件

接口 配置:

export const downloadDescription = (params) => {
    return request({
        method: 'GET',
        responseType: "blob", // 这行配置可不能少
        url: "/xxxx/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 使用教程参考链接

 

posted on 2022-04-13 15:21  菜鸟成长日记lx  阅读(9731)  评论(0编辑  收藏  举报