cos-js-sdk 封装预览文件组件

利用腾讯的 cos 对象存储sdk 封装一个可以预览各种类型文件的组件

直接上代码 (框架vue)

<!-- 文件预览 -->
<template>
    <div class="filepreview">
        <div id="custom-mount-box" v-if="fileinfo.file_type == 'file' && !errorPreview"></div>
        <div v-if="fileinfo.file_type == 'video' && !errorPreview" class="preview-video-box flex_center">
          <!-- <div class="video-contain"> -->
            <video :src="fileinfo.url"  controls="controls"></video>
          <!-- </div> -->
            
        </div>
        <div v-if="fileinfo.file_type == 'img' && !errorPreview" class="preview-img-box">
            <img :src="fileinfo.url" alt="">
        </div>
        <div v-if="fileinfo.file_type == 'audio' && !errorPreview">
             <audio controls :src="fileinfo.url"></audio>
        </div>
        <div class="empty" v-if="errorPreview">
            <img src="https://cdn.tqxxkj.cn/static/images/cxjd/pc/nodata.png">
            <p>当前页面不支持该文件格式预览</p>
            <span @click="previewFileIe">其他预览方式</span>
        </div>
    </div>
</template>
<script>
let Base64 = require('js-base64').Base64;
export default {
    name: "filePreview",
    data() {
        return {
            file_detail:{},
            errorPreview:false
        };
    },
    props:['fileinfo'],
    watch: {
        'fileinfo': {
            handler(newVal, oldVal) {
                console.log(newVal,'aaa')
                if (newVal.name) {
                    this.errorPreview=false;
                    if(newVal.file_type == 'file'){
                        this.$nextTick(() => {
                            document.getElementById('custom-mount-box').innerHTML='
'
; this.init(); }) }else if(newVal.file_type != 'video' && newVal.file_type != 'img' && newVal.file_type != 'audio'){ this.errorPreview = true } } }, deep: true, immediate: true }, }, methods: { init(){ var that=this; this.file_detail=this.fileinfo; var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串 var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; //判断是否IE<11浏览器 var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1;//不包含Edge浏览器 var specialFile = ['MP4','MP3', 'RAR', 'ZIP','PSD'];//用来处理不能预览的文件 console.log(this.fileinfo.name,'this.fileinfo.name') var index = this.fileinfo.name.lastIndexOf('.'); var ext = this.fileinfo.name.substr(index + 1); var type = ext.toUpperCase(); if(isIE11||isIE||specialFile.indexOf(type) > -1){ this.errorPreview = true; }else{ setTimeout(function(){ that.previewFile(that.file_detail); },100) } }, async previewFile(item) { console.log(item,'item888') var url = await COSDocPreviewSDK.getPreviewUrl({ objectUrl: item.url, copyable: 0, htmlwaterword: '' }) if(url == ''){ this.errorPreview = true; return; }else{ document.querySelector('#custom-mount-box').style.height="50vh"; document.querySelector('.custom-mount').style.height="50vh"; } var demo = COSDocPreviewSDK.config({ url: url, // 步骤3中获取到的在线文档预览地址 copyable:1, mount: document.querySelector('.custom-mount'), //通用选项,适用于所有类型的文档。 commonOptions: { isShowTopArea: false, //隐藏顶部区域(头部和工具栏)。 isShowHeader: true, //隐藏头部区域。 isBrowserViewFullscreen:false, isIframeViewFullscreen:false, }, //WORD文档相关配置。 wordOptions: { isShowDocMap: true, isBestScale: true }, //PDF文档相关配置。 pdfOptions: { isShowComment: true, isInSafeMode: true }, //演示文档相关配置。 pptOptions: { isShowBottomStatusBar: true } }) // 如果需要对 iframe 进行特殊的处理,可以通过以下方式拿到 iframe 的 dom 对象 // console.log(demo.iframe); // 打开文档结果 var that=this; demo.on('fileOpen', function(data) { // console.log(data); // const pptApp = demo.PPTApplication(); }); }, previewFileIe(item){//预览文件 window.open('https://preview.tq-edu.com/onlinePreview?url='+encodeURIComponent(Base64.encode(this.file_detail.url))); }, }, created(){ // this.$nextTick(()=>{ // document.onselectstart = new Function("event.returnValue=false"); // }) } }; </script> <style> </style> <style lang="scss" scoped> .filepreview{background-color: #ffffff;height: 100%;} .main1{width: 100%;padding:0;max-width: 100%; } .radius-box{padding: 10px;} /*#custom-mount-box{width: 100%;height: 100vh;} .custom-mount{width: 100%;height: 100vh;}*/ .empty{text-align: center;background-color: #ffffff;padding: 30px 0;height: 100%;} .empty img{width: 60%;max-width: 400px;} .empty p{font-size: 18px;margin-top: 20px;margin-bottom:10px; color: #828282;} .empty span{font-size: 18px;color: #3F85ED;cursor: pointer;} .preview-img-box{width: 100%;max-height: 400px;} .preview-img-box img{max-width: 100%;max-height: 100%;} .preview-video-box{width: 100%;height: vw(494);} .preview-video-box video{max-height: 100%;} </style>

js-base64 依赖记得下载

说下几个注意点 我这个是项目中的代码 其中的fileInfo是在父组件中传递过来的,包含文件的type和url 使用的时候只要传递相同格式的数据就行

{
	type: '文件格式', // xlsx docx pdf等
	url: '文件url'
}

需要的数据格式就是这样 字段名不一致可以自行修改

你可能感兴趣的:(javascript,vue.js,前端)