安装 docx-preview
npm i docx-preview -S
<template>
<div>
<el-table :data="listData">
<el-table-column label="文件名称" prop="fileName">
<template slot-scope="scope">
<el-button
@click.native="
previewFile(
scope.row.fileId, // 文件id
scope.row.fileType,// 文件类型
scope.row.fileName,// 文件名称
)
"
type="text"
>{{ scope.row.fileName }}</el-button
>
</template>
</el-table-column>
</el-table>
<!-- 文件预览 -->
<el-dialog
append-to-body
:visible.sync="showPreview"
title="预览"
:show-close="true"
class="dialog-preview"
fullscreen
>
<div style="width: 100%;height: 100%;">
<div style="float: right; margin-top: -32px">
<el-button type="text" size="mini" @click.native="downloadFile"
>下载</el-button
>
</div>
<div v-if="docFile">
<div ref="file"></div>
</div>
<div v-else>
<iframe
:src="pdfUrl"
frameborder="0"
style="width: 100%; height: 100%;height: 100vh"
></iframe>
</div>
</div>
</el-dialog>
</div>
</template>
<script>
import {readFile} from '@/api.js'
// 定义blob对应的type
const fileTypeMap = {
".xls": "application/vnd.ms-excel",
".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
".doc": "application/msword",
".docx":
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
".pdf": "application/pdf",
".ppt": "application/pdf",
".pptx":
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
".png": "image/png",
".gif": "image/gif",
".jpeg": "image/jpeg",
".jpg": "image/jpeg",
".txt": "text/plain",
};
export default {
data(){
return {
showPreview:false,//预览弹窗
pdfUrl:'',
docFile:'',
fileObj : {
fileId:'',
fileType:'',
fileName:'',
}
}
},
methods:{
// // 预览文件
previewFile(fileId, fileType, fileName) {
this.pdf = "";
this.docFile = "";
this.showPreview = true;
this.fileObj = {
fileId,
fileType,
fileName,
};
readFile({ fileId: fileId }).then((res) => {
let type = "";
if (fileType) {
type = fileTypeMap[fileType];
if (fileType === ".pdf" || fileType === ".txt") {
// pdf和文本类型的,用iframe打开
const blob = new Blob([res], { type }); // type必传
this.pdfUrl = window.URL.createObjectURL(blob);
}
if (fileType === ".doc" || fileType === ".docx") {
// word类型的用docx-preview插件
this.docFile = true;
let docx = require("docx-preview");
this.$nextTick(() => {
docx
.renderAsync(res, this.$refs.file)
.then((x) => console.log("docx: finished", x));
});
}
}
});
},
// 下载文件
downloadFile() {
let fileType = this.fileObj.fileType;
let fileId = this.fileObj.fileId;
let fileName = this.fileObj.fileName;
downloadFile({ fileId: fileId })
.then((res) => {
if (navigator.msSaveBlob) {
window.navigator.msSaveOrOpenBlob(res, fileName);
}
const link = document.createElement("a");
const binaryData = [];
binaryData.push(res);
link.href = window.URL.createObjectURL(
new Blob(binaryData, {
type: fileTypeMap[fileType],
})
);
link.download = fileName;
link.style.display = "none";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
})
.catch((err) => {
console.log(err, "errdownloadFile");
});
},
}
}
</script>