Vue2实现txt文件在线预览的代码示例
作者:_Feliz
txt文件在线预览不需要下载另外的插件,主要有两种形式,一种是上传完成后实现预览;另一种是后端提供文件下载接口,获取文件在线地址实现预览;本文给大家介绍了Vue2实现txt文件在线预览的代码示例,需要的朋友可以参考下
一、上传完成后实现预览
<template>
<!-- txt文件预览 -->
<div>
<el-dialog
title="文件预览"
:visible="dialogVisible"
show-close
append-to-body
width="60%"
:before-close="cancelDialog"
>
<input type="file" @change="handleFileChange">
<div class="panel-box" v-html="txt"></div>
<div slot="footer" class="dialog-footer tc">
<button class="btn-submit btn-submit-sm" @click="cancelDialog()">关闭</button>
</div>
</el-dialog>
</div>
</template>
<script>
export default {
name:'txtFilePreview',
data() {
return {
dialogVisible:false,
txt:'',
};
},
methods: {
previewFile(){
this.dialogVisible = true;
},
handleFileChange(e){
const file = e.target.files[0];
if (!file) {
return;
}
const that = this;
const reader = new FileReader();
reader.onload = function(e) {
that.txt = e.target.result.split('\n').join('<br />');
};
reader.onerror = function(error) {
console.error('Error: ', error);
};
reader.readAsText(file);
},
cancelDialog(){
this.dialogVisible = false;
},
}
};
</script>
<style lang="scss" scoped>
</style>实现效果:

二、后端提供文件下载接口实现预览
<template>
<!-- txt文件预览 -->
<div>
<el-dialog
title="文件预览"
:visible="dialogVisible"
show-close
append-to-body
width="60%"
:before-close="cancelDialog"
>
<div class="panel-box" v-html="txt"></div>
<div slot="footer" class="dialog-footer tc">
<button class="btn-submit btn-submit-sm" @click="cancelDialog()">关闭</button>
</div>
</el-dialog>
</div>
</template>
<script>
export default {
name:'txtFilePreview',
data() {
return {
dialogVisible:false,
txt:'',
};
},
methods: {
previewFile(event,docId) {
event.stopPropagation();
this.dialogVisible = true;
const inParam = {
DOC_ID: docId,
STAFF_ID: this.$store.getters.staffId,
STAFF_NAME: this.$store.getters.staffName,
SYS_USER_CODE: this.$store.getters.systemUserCode
};
const loading = this.$commonUtil.loading.open()
this.$txtPreview(this.mciApi.common.file.downFile, { ...inParam }).then(r => {
loading.close()
// 根据文件地址解析txt文件内容
this.$axios.get(r,{
responseType:"blob",
transformResponse: [
async (data)=>{
return await this.transformData(data);
},
],
}).then(res=>{
res.data.then((data)=>{
this.txt = data ? data.split('\n').join('<br />') : '';
})
})
}).catch((e) => {
loading.close()
})
},
transformData(data){
return new Promise((resolve)=>{
let reader = new FileReader();
reader.readAsText(data,'UTF-8');
reader.onload = ()=>{
resolve(reader.result)
}
})
},
cancelDialog(){
this.dialogVisible = false;
},
}
};
</script>
<style lang="scss" scoped>
</style>Tips:
$txtPreview:是封装后的post请求;
this.mciApi.common.file.downFile:是后端提供的文件下载方法,返回一个文件流数据。获取数据后将文件流进行地址转换作为结果返回。
文件流转url地址:
const blob = new Blob([content], { type: 'application/text' });
const url = window.URL.createObjectURL(blob);实现效果:

到此这篇关于Vue2实现txt文件在线预览的代码示例的文章就介绍到这了,更多相关Vue2 txt文件在线预览内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
