vue 文件预览
Posted 泳之
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vue 文件预览相关的知识,希望对你有一定的参考价值。
npm install --save vue-pdf
------------------------------------------------------------------
<template>
<el-dialog title="文件预览" :visible.sync="visible">
<div slot="title" class="toolbar">
<span>文件预览</span>
<el-button
type="plain"
id="download-btn"
icon="el-icon-download"
title="下载"
@click="handleDownload"
></el-button>
</div>
<div class="file-preview" v-loading="loading">
<el-image :src="url" v-if="fileType == \'image\'"> </el-image>
<vue-pdf ref="pdf" :src="url" v-if="fileType == \'pdf\'"> </vue-pdf>
</div>
</el-dialog>
</template>
<script>
import { downLoadFile } from "@/api/upload";
import vuePdf from "vue-pdf";
import FileSave from "file-saver";
export default {
name: "FilePreview",
components: {
vuePdf,
},
data() {
return {
visible: false,
loading: false,
blob: null,
url: "",
fileType: "",
fileName: "",
};
},
methods: {
async handleInit(id, name) {
// 初始化
Object.assign(this.$data, this.$options.data());
this.fileName = name;
this.handleFileType();
this.visible = this.fileType != "other";
await this.handleBlobData(id);
if (this.fileType == "other") {
this.handleDownload();
} else {
this.url = window.URL.createObjectURL(this.blob);
}
},
handleFileType() {
let suffix = this.fileName.replace(/.+\\./, "");
if (["jpg", "jpeg", "png"].includes(suffix)) {
this.fileType = "image";
} else if (suffix == "pdf") {
this.fileType = "pdf";
} else {
this.fileType = "other";
}
},
async handleBlobData(id) {
this.loading = true;
const res = await downLoadFile(id);
this.loading = false;
return new Promise((resolve) => {
if (res) {
this.blob = new Blob([res]);
}
resolve();
});
},
handleDownload() {
FileSave.saveAs(this.blob, this.fileName);
},
},
};
</script>
<style lang="scss" scoped>
::v-deep .el-dialog {
height: 90vh;
margin: 3vh auto !important;
.toolbar {
width: 100%;
display: flex;
justify-content: space-between;
align-items: center;
}
.el-dialog__body {
padding-top: 0;
}
.el-button {
border: none;
font-size: 18px;
margin: -5px 40px 0;
&:hover {
color: #1d69ce;
}
}
}
.file-preview {
height: 80vh;
#download-btn {
float: right;
margin: 2vh 0 0;
}
.el-image {
width: 100%;
height: 100%;
text-align: center;
padding: 10%;
}
}
</style>
----------------------------------------------------------
用法
<dialog-file-preview ref="filePreview"></dialog-file-preview>
import DialogFilePreview from "@/components/DialogFilePreview.vue";
components: { DialogFilePreview },
handlePreview (id, name) {
if (id && name) {
this.$refs.filePreview.handleInit(id, name);
} else {
return;
}
},
以上是关于vue 文件预览的主要内容,如果未能解决你的问题,请参考以下文章