在线预览pdf或者播放视频的页面Vue代码
主要通过后端返回文件流,前端进行处理展示。后端返回流的代码省略,只展示前端代码,其他vue引入这个preview-file文件,调用previewFile这个方法即可,this.$refs.previewFileRef.previewFile(row)
<template>
<div class="preview-file">
<el-dialog
width="80%"
:top="'10px'"
class="viewItemFileDialog"
:fullscreen="whetherFullScreen"
:visible.sync="dialogVisible"
@close="closeDialog"
>
<span slot="title" style="font-size: 18px">
<span>预览</span>
<i style="position: absolute; right:50px; top: 15px"
class="el-icon-full-screen"
@click="fullscreenClick"
></i>
</span>
<div v-if="type == 'pdf'" v-loading="loading">
<iframe
:src="pdfUrl"
type="application/x-google-chrome-pdf"
width="100%"
height="100%"
style="height: 800px"
/>
</div>
<div v-if="type == 'mp4'" v-loading="loading">
<video width="100%" height="100%" controls>
<source :src="videoUrl" type="video/mp4" />
</video>
</div>
</el-dialog>
</div>
</template>
<script>
import { downloadFile} from '@/api/message'
export default {
name: 'previewFile',
data: function() {
return {
whetherFullScreen: false,
loading: false,
dialogVisible: false,
type: 'pdf',
pdfUrl: '',
videoUrl: ''
}
},
methods: {
// 处理视频播放,关闭弹框,视频还在播放的bug
closeDialog() {
this.whetherFullScreen = false
if (this.type == 'mp4' && document.getElementById('video')) {
document.getElementById('video').pause()
}
},
fullscreenClick() {
this.whetherFullScreen = !this.whetherFullScreen
},
previewFile(row) {
if (row && row.fileCode && row.fileExtension) {
this.dialogVisible = true
this.loading = true
downloadFile(row.fileCode)
.then(res => {
if (res instanceof Blob) {
this.type = row.fileExtension
if (this.type == 'pdf') {
let blob = new Blob([res], { type: 'application/pdf' })
this.pdfUrl = URL.createObjectURL(blob)
console.log(this.pdfUrl)
this.loading = false
} else if (this.type == 'mp4') {
let blob = new Blob([res])
this.videoUrl = URL.createObjectURL(blob, { type: 'video/mp4' })
console.log(this.videoUrl)
this.loading = false
} else {
this.loading = false
this.$message.error('暂时只支持PDF和MP4在线预览,其他格式不支持')
}
} else {
this.loading = false
this.$message.error('处理失败')
}
})
.catch(() => {
this.loading = false
this.$message.error('处理失败')
})
}
}
}
}
</script>
<style scoped>
</style>
downloadFile的写法
export function downloadFile(fileName) {
return request({
url: baseUrl + `/${fileName}`,
responseType: 'blob',
method: 'get'
})
}
pdf的效果
视频的效果
后端返回文件流,页面实现下载文件功能Vue代码
按钮点击调用downloadCurFile方法即可
downloadCurFile(row) {
if (row && row.fileCode) {
downloadFile(row.fileCode)
.then(res => {
if (res instanceof Blob) {
const link = document.createElement('a')
link.download = row.fileName
link.href = window.URL.createObjectURL(res)
link.click()
} else {
this.$message.error('处理失败')
}
})
.catch(() => {
this.$message.error('处理失败')
})
}
},