VUE中实现PDF,Word,excel文件下载预览等功能

进行文件下载的话是不需要插件之类的代码如下:

{
          label: "下载",
          icon: "",
          clickFun: function (rowInfo, item, scope) {
            console.log(rowInfo);
            let data = {
              id: rowInfo.id,
            };//获取用户当前点击文件的id
            let fileType = ""; // 定义文件类型变量
            if (rowInfo.format === "xlsx" || rowInfo.format === "xls") {
              fileType = "application/vnd.ms-excel";
            } else if (rowInfo.format === "pdf") {
              fileType = "application/pdf";
            } else if (
              (rowInfo.format === "doc") |
              (rowInfo.format === "docx")
            ) {
              fileType = "application/msword";
            } else if (rowInfo.format === "txt") {
              fileType = "text/plain";
            } else if (
              rowInfo.format === "jpg" ||
              rowInfo.format === "jpeg"
            ) {
              fileType = "image/jpeg";
            } else if (rowInfo.format === "png") {
              fileType = "image/png";
            } else if (rowInfo.format === "gif") {
              fileType = "image/gif";
            } else if (rowInfo.format === "zip") {
              fileType = "application/zip";
            } else {
              fileType = "application/octet-stream"; // 默认文件类型为二进制流
            }
            this.$axios({
              method: "post",
              url: this.apiUrl.getUrl("standardDocfileDownload"),//请求地址
              responseType: "arraybuffer",
              headers: {
                "Content-Type": "application/json",
              },
              data: data,
            })
              .then((response) => {
                const blob = new Blob([response], {
                  type: fileType, // 根据文件类型设置响应类型
                });
                const downloadUrl = URL.createObjectURL(blob);
                const link = document.createElement("a");
                link.href = downloadUrl;
                link.download = `${rowInfo.chnName}.` + rowInfo.format; // 根据文件类型设置文件名后缀
                link.click();
                URL.revokeObjectURL(downloadUrl);
              })
              .catch((error) => {
                console.error("请求出错", error);
              });
          }.bind(this),
        },

文件预览如下:
使用插件:vue-office
gitee地址:https://gitee.com/ye-jizeng/vue-office?_from=gitee_search
具体使用可查看gitee中的使用案例
当前组件仅支持docx、pdf、excel,不支持doc等老版本excel或word文件,具体文件差异请自行百度


      <div>
          <vue-office-excel :src="excelBlob" />
      </div>

      <div>
        <tong-dialog
          :visible.sync="wordyulan"
          width="1600px"
          height="80%"
          title="预览Word"
        >
          <vue-office-docx :src="docxS" />
        </tong-dialog>
      </div>
      
{
      label: "预览",
      icon: "",
      clickFun: function (rowInfo, item, scope) {
        console.log(rowInfo);
        let data = {
          id: rowInfo.id,
        };
        let fileType = ""; // 定义文件类型变量
        if (rowInfo.format === "xlsx" || rowInfo.format === "xls") {
          this.$axios({
            method: "post",
            url: this.apiUrl.getUrl("standardDocfileDownload"), // 后端接口地址
            responseType: "arraybuffer", // 响应类型为arraybuffer
            headers: {
              "Content-Type": "application/json", // 请求头设置
            },
            data: data, // 请求数据,根据后端接口要求进行设置
          })
            .then((response) => {
              // 将ArrayBuffer转换为Blob对象
              const blob = new Blob([response], {
                type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
              }); // 根据实际情况设置正确的MIME类型
              // 将Blob对象转换为URL,以便预览
              const url = URL.createObjectURL(blob);
              // 将转换后的URL赋值给excelBlob变量,以便在组件中使用
              this.excelBlob = url;
            })
            .catch((error) => {
              console.log(error);
            })
            .finally(() => {});
        } else if (rowInfo.format === "pdf") {
          fileType = "application/pdf";
        } else if (
          (rowInfo.format === "doc") |
          (rowInfo.format === "docx")
        ) {
          this.$axios({
            method: "post",
            url: this.apiUrl.getUrl("standardDocfileDownload"), // 后端接口地址
            responseType: "arraybuffer", // 响应类型为arraybuffer
            headers: {
              "Content-Type": "application/json", // 请求头设置
            },
            data: data, // 请求数据,根据后端接口要求进行设置
          })
            .then((response) => {
              // 将ArrayBuffer转换为Blob对象
              const blob = new Blob([response], {
                type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
              }); // 根据实际情况设置正确的MIME类型
              // 将Blob对象转换为URL,以便预览
              const url = URL.createObjectURL(blob);
              // 将转换后的URL赋值给excelBlob变量,以便在组件中使用
              this.docxS = url;
            })
            .catch((error) => {
              console.log(error);
            })
            .finally(() => {});
        } else if (rowInfo.format === "txt") {
          fileType = "text/plain";
        } else if (
          rowInfo.format === "jpg" ||
          rowInfo.format === "jpeg"
        ) {
          fileType = "image/jpeg";
        } else if (rowInfo.format === "png") {
          fileType = "image/png";
        } else if (rowInfo.format === "gif") {
          fileType = "image/gif";
        } else if (rowInfo.format === "zip") {
          fileType = "application/zip";
        } else {
          fileType = "application/octet-stream"; // 默认文件类型为二进制流
        }
        this.$axios({
          method: "post",
          url: this.apiUrl.getUrl("standardDocfileDownload"),
          responseType: "arraybuffer",
          headers: {
            "Content-Type": "application/json",
          },
          data: data,
        })
          .then((response) => {
            const blob = new Blob([response], {
              type: fileType, // 根据文件类型设置响应类型
            });
            const downloadUrl = URL.createObjectURL(blob);

            // 自动打开文件
            if (fileType === "application/pdf") {
              // 如果是 PDF 文件,使用 PDF.js 打开
              window.open(downloadUrl, "_blank");
            } else if (
              rowInfo.format === "docx"
            ) {
              this.wordyulan = true;
            }else if (
              rowInfo.format === "doc"
            ) {
              this.tongMessage("success", "暂不支持的文件类型,请进行下载后进行预览");
            } else if (
              rowInfo.format === "xlsx"
            ) {
              this.excelyulan = true;
            }else if (
              rowInfo.format === "xls"
            ) {
              this.tongMessage("success", "暂不支持的文件类型,请进行下载后进行预览");
            } else if (rowInfo.format === "txt") {
              // 如果是文本文件,使用 FileReader 读取文件内容并转换为 UTF-8 编码
              const reader = new FileReader();
              reader.onload = (e) => {
                const data = e.target.result;
                const popupWindow = window.open("", "_blank");
                popupWindow.document.write("<pre>" + data + "</pre>");
              };
              reader.readAsText(blob, "UTF-8");
            } else {
              // 其他文件类型,使用默认应用程序打开
              window.open(downloadUrl);
            }
          })
          .catch((error) => {
            console.error("请求出错", error);
          });
      }.bind(this),
    },

后端返回内容格式如下
在这里插入图片描述
最终效果如下:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
这是下载成功之后的效果,文件都可正常打开内容没问题

预览和下载都是使用的同一个接口,都是下载!

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值