前端:接口返回文件流,pdf,excel等文件实现下载及预览

1,380 阅读1分钟

写在前面

    在做网站的过程中,遇到预览和下载的需求是很常见的,在此记录实现过程,以供有需要的朋友使用和学习。

文件流

    接口返回的报文示例如下图,为文件流格式:

image.png

下载

    以下为下载实现代码,根据备注稍作修改即可直接使用:

// 下载
ticketFaceDownload() {
       this.$http({
        url: "/xxxxxx/xxxxx/xxxxx", // 接口地址
        method: "get",
        responseType: "blob", // 需要加上
        params: { // 接口需要的参数,视个人情况而定
          ticketBizId:this.ViewData.ticketId,
          packageNo: this.ViewData.superInfoList[0].packageNo,
          ticketRange: this.ViewData.superInfoList[0].ticketRange
        },
      }).then((res) => {
        const blob = new Blob([res.data]); //excel,pdf等
        const href = URL.createObjectURL(blob); //创建新的URL表示指定的blob对象
        const a = document.createElement("a"); //创建a标签
        a.style.display = "none";
        a.href = href; // 指定下载链接
        a.download = '票面凭证.pdf'; //指定下载文件名
        a.click(); //触发下载
        URL.revokeObjectURL(a.href); //释放URL对象
      });
   },

预览

        以下为预览实现代码,根据备注稍作修改即可直接使用:

ticketFaceView() {
      this.$http({
        url: "/xxxxxx/xxxxx/xxxxx", // 接口地址
        method: "get",
        responseType: "blob", // 需要加上
        params: { // 接口需要的参数,视个人情况而定
          ticketBizId:this.ViewData.ticketId,
          packageNo: this.ViewData.superInfoList[0].packageNo,
          ticketRange: this.ViewData.superInfoList[0].ticketRange
        },
      }).then((res) => {
         const pdfFile = window.URL.createObjectURL(
              new Blob([res.data], { type: "application/pdf" })
            );
            // 跳转页面预览
            window.open(pdfFile);
            URL.revokeObjectURL(pdfFile); //释放URL对象
      });
    },

写在最后

        以上就是今天的所有内容啦,再会朋友们。