Vue2中使用iframe展示文件流(PDF)以及blob类型接口错误展示返回值

需求

使用iframe展示后端接口传输来的文件流(pdf),如果接口返回错误则弹出提示

html部分

<iframe :src="url" width="100%" />

接口部分

    // 接口封装已忽略,注意:如需接口接收文件流,请在请求中加入responseType: 'blob'以及type: "application/json;chartset=UTF-8"
    function ReportExportPDF(data) {
      return request({
        url: data.month ? `/report/export/pdf/${data.year}/${data.month}` : `/report/export/pdf/${data.year}`,
        method: 'post',
        responseType: 'blob',
        type: "application/json;chartset=UTF-8"
      })
    }

js部分

export default {
  data() {
    return {
      url: ''  // 用于展示文件
    }
  },
  methods: {
    ReportExportPDF(params).then(res => {
      console.log(res);
      // 此处的res,如果接口返回错误也会因为请求中设置了responseType: 'blob'所以会返回成文件流类型
      // 因此我们需要对res进行判断:如果返回失败,则res的type为'application/json',如果返回成功则是正常的文件流。
      if (res.type === 'application/json') {
        // 因为是文件流,所以我们需要从文件中读取返回值,使用FileReader
        const reader = new FileReader();
        const that = this;
        reader.onload = function () {
          // 使用JSON读取返回值
          const { msg } = JSON.parse(reader.result);
          // 使用弹出提示展示错误信息(这里用的是elementUI)
          that.$message.error(msg);
          return false;
        }
        // 本行将在onload前执行,使用readAsText读取res中的值
        reader.readAsText(res);
        return;
      } 
      // 如果正常返回,先将文件流的type使用blob转换成pdf类型
      let blob = new Blob([res], {
        type: "application/pdf;chartset=UTF-8"
      })
      // 然后使用window.URL.createObjectURL()方法将blob转成url地址赋值给iframe
      this.url = window.URL.createObjectURL(blob);
    })
  }
}
posted @ 2024-04-08 17:19  仲夏今天也在写前端  阅读(854)  评论(0编辑  收藏  举报