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

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;
      });
    },
}
    

 如果是excel、doc 、txt等文档,一般是让后端转成PDF,再传给前端。

遇到的问题:后端使用java,发现预览失败.

解决方法是在传参的时候添加类型responseType: "arraybuffer",在接受的时候指定blob类型,如

type: "application/pdf"

整体代码如下:

//预览接口  
Preview: (config, params) => {
    return service.post("api/gridSend/Preview", params, config);
  },
/** 插槽 下载预览
			 * @param val.val ---当行数据
			 * @param val.btnflag  ==1是预览,==2 是下载
			 */
			getDJlook(val) {
				if (val.val.IsDownLoad !== "3" || val.val.IsDownLoad == null) {
					this.$message({
						message: "请先点击【一键拉取】进行下载作业系统的文档数据,再进行操作!",
						type: "warning",
					});
					return;
				}

				if (val.btnflag == "1") {
					let param = {
						Id: val.val.MongodbIds,
						FileName: val.val.FileName
					};
					this.upFileLoading = true;
					this.$luleApi
						.Preview({
							responseType: "arraybuffer"
						}, param)
						.then((res) => {
							if (
								JSON.parse(res.config.data).FileName.search("xls") != -1 ||
								JSON.parse(res.config.data).FileName.search("doc") != -1 ||
								JSON.parse(res.config.data).FileName.search("pdf") != -1
							) {
								let blob = new Blob([res.data], {
									type: "application/pdf"
								});
								let fileURL = URL.createObjectURL(blob);

								this.fileURLOther = fileURL;
								this.fileURLOtherTitle = JSON.parse(res.config.data).FileName; //弹窗title
								this.upFileLoading = false; //loading 取消加载
								this.dialogfileURLOther = true;
							
							} else if (
								JSON.parse(res.config.data).FileName.search("txt") != -1
							) {
								let blob = new Blob([res.data], {
									type: "application/pdf"
								});
								let fileURL = URL.createObjectURL(blob);
								//#region 创建a标签
								const link = document.createElement("a");
								link.href = fileURL;
								link.target = "_blank";
								document.body.appendChild(link);
								link.click();
								document.body.removeChild(link);
								this.upFileLoading = false; //loading 取消加载
								//#endregion

								//#region ifame
								// this.fileURLOther = fileURL;
								// this.fileURLOtherTitle = JSON.parse(res.config.data).FileName;//弹窗title
								// this.upFileLoading = false;//loading 取消加载
								// this.dialogfileURLOther = true
								//#endregion
							} else if (
								JSON.parse(res.config.data).FileName.search("png") != -1 ||
								JSON.parse(res.config.data).FileName.search("jpg") != -1 ||
								JSON.parse(res.config.data).FileName.search("jpeg") != -1
							) {
								if (window.URL && window.URL.createObjectURL) {
									let blob = new Blob([res.data], {
										type: "image/png"
									});
									let fileURL = window.URL.createObjectURL(blob);
									window.open(fileURL);
								} else {
									// 进行降级处理,将 Blob 转为 Base64 编码字符串
									const reader = new FileReader();
									reader.onloadend = function() {
										const base64Data = reader.result;
										const img = document.createElement("img");
										img.src = base64Data;
										document.body.appendChild(img);
									};
									reader.readAsDataURL(new Blob([res.data]));
								}
								this.upFileLoading = false; //loading 取消加载
							} else {
								this.$message({
									message: "该文件类型不支持预览,请选择其他文件类型!",
									type: "warning",
								});
								return;
							}
						})
						.catch((err) => {
							this.upFileLoading = false;
						});
				}else {
					//下载
					localStorage.setItem("xzOK", "1"); //记录触发了下载
					let param = {
						Id: val.val.MongodbIds,
						FileName: val.val.FileName,
						Project: this.ProjectID,
					};
					this.$luleApi
						.DownloadFileById({
							responseType: "arraybuffer"
						}, param)
						.then((res) => {
							// const fileName = JSON.parse(res.config.data).FileName;
							const fileName = val.val.FileName;
							const blob = new Blob([res.data], {
								type: "application/octet-stream",
							});
							const url = window.URL.createObjectURL(blob);

							const link = document.createElement("a");
							link.href = url;
							link.download = fileName;
							document.body.appendChild(link);
							link.click();
							this.rerender();
							document.body.removeChild(link);
							URL.recycleObjectURL(url);
							localStorage.setItem("xzOK", "0"); //下载成功后,归0
						})
						.catch((err) => {
							this.upFileLoading = false;
						});
				}
			},

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

Logo

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

更多推荐