VUE在线展示office文件

根据文件的类型用不同的方式处理,例如对于图片直接显示,对于 PDF 文件使用 PDF.js 加载,对于 Office 文件,使用 Microsoft Office 的在线预览功能。

loadFile() {
    // 定义文件连接
    let link = this.filePath;

    // 获取文件类型
    const type = link.substring(link.lastIndexOf(".") + 1);// 如果文件类型为图像
    if (this.isImg(type)) {
        this.showImg = true;
        this.imgUrl = link; // 设置图像URL
        this.loading = false; // 加载完成
    } 

    // 如果文件类型为pdf
    else if (type == "pdf") {
        this.isPdf = true;
        const fileName = link.substring(0, link.lastIndexOf(".") + 1) + "pdf";

        var loadingTask = pdf.createLoadingTask({
            url: fileName,
            httpHeaders: this.header
        });

        this.src = loadingTask;

        loadingTask.promise
            .then(pdf => {
                this.pageCount = pdf.numPages; // 设置PDF页面数
                this.loading = false; // 加载完成
            })
            .catch(err => {
                // 加载失败,显示错误信息
                this.loading = false;
                this.$message({
                    message: "加载失败!错误代码:" + err.details,
                    type: "error",
                    duration: 5 * 1000
                });
            });
    } 

    // 如果文件类型为Office文件
    else if (this.isFiles(type)) {
        // 使用微软Office在线查看器预览文件
        this.src = https://view.officeapps.live.com/op/view.aspx?src=${process.env.VUE_APP_PREVIEW_URL}${this.filePath};
        this.loading = false; // 加载完成
    } 
    
    else {
        this.loading = false;
    }
},
isImg(type) {
    // 检查文件类型是否在允许的图像类型列表中
    return this.imgType.indexOf(type) !== -1;
},
isFiles(type) {
    // 检查文件类型是否在允许的文件类型列表中
    return this.fileType.indexOf(type) !== -1;
},

 

posted @ 2024-04-23 17:34  天辰啦啦啦  阅读(235)  评论(0)    收藏  举报