实现原理:点击“预览”按钮,通过向后端发起请求,获取到文件流,再打开。

1. 在新页面打开,使用window.open()

 <el-button slot="trigger" size="small" type="primary" plain @click="openPDF">
          点击在线预览pdf
</el-button>
import axios from "axios";
data() {
    return {
      annex: { id: null, name: "", url: "" },
    }
}

methods:{
  openPDF() {
      axios({
        method: "get",
        url: this.annex.url,//文件的url
        params: {
          fileId: this.annex.id,//文件的id
        },
        responseType: "blob",
      }).then((res) => {
        // loading.close();
        console.log("res", res);
        if (res.status == "500") {
          this.$message({
            message: "下载失败!",
            type: "error",
          });
          return;
        }
        //文件以pdf形式进行预览
        let blob = new Blob([res.data], {
          type: "application/pdf;chartset=UTF-8",
        });
        let fileURL = URL.createObjectURL(blob);
        window.open(fileURL);
      });
    },
}
    

2. 在当前页面打开pdf  ,使用的是iframe 

 <el-button slot="trigger" size="small" type="primary" plain @click="openPDF">
          预览
</el-button>
<iframe :src="fileURLOther"></iframe> 

import axios from "axios";
data() {
    return {
      fileURLOther: "",
      annex: { id: null, name: "", url: "" },
    }
}

methods:{
  openPDF() {
      axios({
        method: "get",
        url: this.annex.url,//文件的url
        params: {
          fileId: this.annex.id,//文件的id
        },
        responseType: "blob",
      }).then((res) => {
        // loading.close();
        console.log("res", res);
        if (res.status == "500") {
          this.$message({
            message: "下载失败!",
            type: "error",
          });
          return;
        }
        //文件以pdf形式进行预览
        let blob = new Blob([res.data], {
          type: "application/pdf;chartset=UTF-8",
        });
        let fileURL = URL.createObjectURL(blob);
        this.fileURLOther = fileURL;
      });
    },
}
    

转发来自/参考资料:https://blog.csdn.net/qq_39877681/article/details/125317931

GitHub 加速计划 / vu / vue
207.53 K
33.66 K
下载
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
最近提交(Master分支:2 个月前 )
73486cb5 * chore: fix link broken Signed-off-by: snoppy <michaleli@foxmail.com> * Update packages/template-compiler/README.md [skip ci] --------- Signed-off-by: snoppy <michaleli@foxmail.com> Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com> 4 个月前
e428d891 Updated Browser Compatibility reference. The previous currently returns HTTP 404. 4 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐