页面:
<el-dialog
title="在线预览"
:visible.sync="dialogVisible"
width="80%"
v-dialogDrag
class="pub_dialog"
:before-close="handleClose">
<div v-show="docx">
<div class="docWrap" style="background-color: white">
<!-- 预览文件的地方(用于渲染) -->
<div ref="file" style="background-color: white"></div>
</div>
</div>
<div v-show="pdf">
<iframe
:src="pdfurl"
type="application/x-google-chrome-pdf"
style="width: 100%;height: 900px;"
/>
</div>
<div v-show="excel">
<div class="excel-view-container">
<div id="excelView" v-html="excelView" style="width: 90%;height: 900px;margin-left: 5%"></div>
</div>
</div>
</el-dialog>
js:
import XLSX from 'xlsx/xlsx.js'
import VueDocPreview from 'vue-doc-preview'
export default {
components: { VueDocPreview },
data(){
return{
doc : false;
pdf : false;
excel : false;
// 还有其他的自行补充定义
};
},
methods:{
openDialog(row){
this.doc = false;
this.pdf = false;
this.excel = false;
console.log(row.path)
this.dialogVisible = true
if(row.name.endsWith('docx')){
this.docx = true;
axios
.request({
method: "GET", //这个不解释了吧
url: url + '/doc/getFile?path=' + encodeURIComponent(row.path), //编码
responseType: "blob", //告诉服务器想到的响应格式
})
.then((res) => {
console.log(res)
if (res) {
let docx = require("docx-preview");
docx.renderAsync(res.data, this.$refs.file);
console.log(res.data)
} else {
this.$notify.error({ title: "失败", message: "接口请求失败" });
this.loading = false;
}
})
.catch(function (error) {
this.$notify.error({ title: "失败", message: "接口请求失败" });
console.log(error);
this.loading = false;
});
}else if(row.name.endsWith('pdf')){
this.pdf = true;
axios
.request({
method: "GET", //这个不解释了吧
url: url + '/doc/getFile?path=' + row.path,
responseType: "blob", //告诉服务器想到的响应格式
headers: {
"Content-Type": "application/pdf;charset=UTF-8",
},
})
.then((res) => {
console.log(res);
if (res) {
let blob = new Blob([res.data], { type: "application/pdf" });
const url = URL.createObjectURL(blob);
console.log(url);
this.pdfurl = url;
} else {
this.$notify.error({ title: "失败", message: "接口请求失败" });
}
})
.catch(function (error) {
this.$notify.error({ title: "失败", message: "接口请求失败" });
console.log(error);
});
}else if(row.name.endsWith('xlsx') || row.name.endsWith('xls')){
this.excel = true;
axios
.request({
method: "GET", //这个不解释了吧
url: url + '/doc/getFile?path=' + row.path,
responseType: "arraybuffer", //告诉服务器想到的响应格式
headers: {
"Content-Type":
"application/vnd.ms-excel;application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
},
})
.then((res) => {
if (res) {
const workbook = XLSX.read(new Uint8Array(res.data), {
type: "array",
}); // 解析数据
const worksheet = workbook.Sheets[workbook.SheetNames[0]]; // workbook.SheetNames 下存的是该文件每个工作表名字,这里取出第一个工作表
this.excelView = XLSX.utils.sheet_to_html(worksheet); // 渲染
this.setStyle4ExcelHtml();
}
})
.catch(function (error) {
console.log(error);
});
}
}
}
}