vue+iview 内网预览(本文重点)+外网预览word、excel、pdf、ppt

16 篇文章 1 订阅

访问内网文件思路如下:
1.后端将word、excel、pdf文件转为二进制文件流 前端将文件流转为html从而实现文件预览
2.pdf没这么复杂具体可看下文
3.ppt的实现方式是后端将ppt转为pdf 然后调用pdf接口

上众所期待的效果图:
word
在这里插入图片描述
excel
在这里插入图片描述
pdf
在这里插入图片描述
一、预览公网上的文件(较为简单 所以放第一)
1.预览公网能访问的文件 使用XDOC就能实现

//file_url是你的文件地址
<a href="http://www.xdocin.com/xdoc?_func=to&_format=html&_cache=1&_xdoc=file_url" target="_blank" rel="nofollow">预览</a>

二、预览内网上的文件(word、excel、pdf本文重点)
前端
word预览-mammoth.js
安装: npm install --save mammoth

excel预览-sheetjs
安装: npm install --save xlsx

2.1接口定义

//预览excel
getExcel(params) {
  return $http.post(`${global.API_URL}/gt1/employeeArchives/getExcel`,params,{
    responseType: 'arraybuffer'
  });
},
//预览word
getWord(params) {
  return $http.post(`${global.API_URL}/gt1/employeeArchives/getWord`,params,{
    responseType: 'arraybuffer'
  });
},
//预览pdf
getPdf(params) {
  return $http.post(`${global.API_URL}/gt1/employeeArchives/getPdf`,params,{
    responseType: 'blob'
  });
}

2.2预览按钮

<Modal title="附件列表" v-model="dialogVisible" width="55%" footer-hide>
    <Table :columns="columns" :data="fileData" style="width: 100.1%;" class="table-css" height="500">
        <!-- 下载 -->
        <template slot-scope="{row,index}" slot="download">
        	<Button type="warning" size="small" @click="preview(row.type)">预览</Button>
        </template>	
    </Table>
</Modal>

2.3预览模式框

<!-- 预览模式框 -->
<Modal v-model="modalPreview" fullscreen title="预览" @on-cancel="cancelPreview">
     <!-- excel -->
     <div v-if="previewType===0">
         <div class="tableExcel" v-html="excelHtml"></div>
     </div>
     <!-- word -->
     <div v-else-if="previewType===1">
         <div class="word" id="wordView"/>
     </div>
     <div slot="footer"></div>
 </Modal>

2.4 引用安装的mammoth和xlsx(供word和excel使用)

import mammoth from "mammoth";
import XLSX from 'xlsx'

2.5初始化参数

data () {
	return {
	    // 预览附件
	    previewType:'',
	    modalPreview:false,
	    excelHtml:'',//excel
	    columns: [
	    {
	        title: '文件名',
	        key: 'fileName'
	    },
	    {
	        title: '文件类型',
	        key: 'fileType'
	    },
	    {
	        title: '操作',
	        slot: 'download',
	        width: 120
	    }],
	    fileData:[{
		    type:0,
		    fileName:"预览excel",
		    fileType:"excel"
		},{
		    type:1,
		    fileName:"预览word",
		    fileType:"word"
		},{
		    type:2,
		    fileName:"预览pdf",
		    fileType:"pdf"
		},{
		    type:3,
		    fileName:"预览ppt",
		    fileType:"ppt"
		}]
	}
},

2.6附件预览方法

methods: {
	/***********************************附件预览***********************************/ 
	/********** 预览excel ***************/ 
	previewExcel:function(){
	    let list=[];
	    let obj={};
	    this.previewType=0;
	    this.modalPreview=true; 
	    this.$api.employeeArchives.getExcel()
	    .then(res => {
	        var data = new Uint8Array(res.data)
	        var workbook = XLSX.read(data, {
	            type: 'array'
	        })
	        this.excelHtml='';
	        for(var i=0;i<workbook.SheetNames.length;i++){
	            const exlname = workbook.SheetNames[i];
	            this.excelHtml+='<h4 style="padding-left:10px;font-size:13px;">'+exlname+'</h4>'+''+XLSX.utils.sheet_to_html(workbook.Sheets[exlname])+'<br>'
	        }
	    })
	},
	/********** 预览word ***************/ 
	previewWord() {
	    this.previewType=1;
	    this.modalPreview=true;
	    this.$api.employeeArchives.getWord()
	    .then(res => {
	        let content = res.data;
	        let blob = new Blob([content], { type: "application/pdf" });
	        let reader = new FileReader();
	        reader.readAsArrayBuffer(blob);
	        reader.onload = function (e) {
	            var arrayBuffer = e.target.result; //arrayBuffer
	            mammoth.convertToHtml({ arrayBuffer: arrayBuffer }).then(displayResult).done();
	        };
	        function displayResult(result) {
	            document.getElementById("wordView").innerHTML =result.value;
	        }
	    })
	},
	/********** 预览pdf ***************/ 
	previewPdf:function(){
	    this.previewType=2;
	    this.$api.employeeArchives.getPdf()
	    .then(res => {
	        const responseData = res.data;
	        if (responseData != null) {
	            let pdfUrl = window.URL.createObjectURL(new Blob([responseData], { type: "application/pdf" }));
	            window.open(pdfUrl)
	        } 
	    })  
	},
	/********** 预览ppt ***************/ 
	previewPPt:function(){
	    this.previewType=3;
	    this.$api.employeeArchives.getPdf()
	    .then(res => {
	        const responseData = res.data;
	        if (responseData != null) {
	            let pdfUrl = window.URL.createObjectURL(new Blob([responseData], { type: "application/pdf" }));
	            window.open(pdfUrl)
	        } 
	    })  
	},
	// 预览
	preview: function(type) {
	    // excel
	    if(type===0){
	        this.previewExcel();
	    }
	    // word
	    else if(type===1){
	         this.previewWord();
	    }
	    // pdf
	    else if(type===2){
	        this.previewPdf();
	    }
	    // ppt
	    else if(type===3){
	        this.previewPPt();
	    }
	},
	// 取消
	cancelPreview:function(){
	    this.excelHtml='';
	}

2.7 word和excel的 css样式(可自行灵活修改

<style scoped>
    /*word样式*/
    .word>>>img
    {
        width: 100%;
    }
    .word
    {
        font-size: 16px;
    }
    /*excel样式*/
    .tableExcel>>>table {
        width: 100%;
        border-right: 1px solid  #e8eaec;
        border-bottom:1px solid  #e8eaec;
        border-collapse: collapse;
        margin: auto;
    }
    .tableExcel>>>table td {
        border-left: 1px solid  #e8eaec;
        border-top: 1px solid  #e8eaec;
        white-space: nowrap;
        padding: .5rem;
    }
    .tableExcel>>>tbody tr:nth-of-type(1) {
        font-weight: bold;
        font-size:13px;
    }
</style>

后端
此文的后端展现如下 为二进制文件流
在这里插入图片描述

以上所见接口的请求都是项目封装过的方法 烦请各自灵活应用

  • 2
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 13
    评论
1. 首先,在项目中引入iviewvue-resource: ``` import Vue from 'vue' import iView from 'iview' import 'iview/dist/styles/iview.css' import VueResource from 'vue-resource' Vue.use(iView) Vue.use(VueResource) ``` 2. 在vue文件中使用iview的Select组件实现省市选择: ``` <template> <div> <Select v-model="province" @on-change="getCityList"> <Option v-for="(item, index) in provinceList" :value="item.id" :key="index">{{ item.name }}</Option> </Select> <Select v-model="city"> <Option v-for="(item, index) in cityList" :value="item.id" :key="index">{{ item.name }}</Option> </Select> </div> </template> <script> export default { data () { return { province: '', city: '', provinceList: [], cityList: [] } }, mounted () { this.getProvinceList() }, methods: { // 获取省份列表 getProvinceList () { this.$http.get('/api/province').then(res => { this.provinceList = res.data }) }, // 获取城市列表 getCityList () { this.$http.get('/api/city', { params: { province: this.province } }).then(res => { this.cityList = res.data }) } } } </script> ``` 3. 在后台实现省市数据接口: 省份接口: ``` app.get('/api/province', function(req, res) { res.json([ {id: 1, name: '北京'}, {id: 2, name: '上海'}, {id: 3, name: '广东省'}, {id: 4, name: '湖南省'} ]) }) ``` 城市接口: ``` app.get('/api/city', function(req, res) { var provinceId = req.query.province var cityList = [] switch(provinceId) { case '1': cityList = [ {id: 101, name: '北京市'}, {id: 102, name: '海淀区'}, {id: 103, name: '朝阳区'}, {id: 104, name: '东城区'}, {id: 105, name: '西城区'} ] break case '2': cityList = [ {id: 201, name: '上海市'}, {id: 202, name: '浦东新区'}, {id: 203, name: '徐汇区'}, {id: 204, name: '黄浦区'}, {id: 205, name: '静安区'} ] break case '3': cityList = [ {id: 301, name: '广州市'}, {id: 302, name: '深圳市'}, {id: 303, name: '珠海市'}, {id: 304, name: '佛山市'}, {id: 305, name: '东莞市'} ] break case '4': cityList = [ {id: 401, name: '长沙市'}, {id: 402, name: '株洲市'}, {id: 403, name: '湘潭市'}, {id: 404, name: '衡阳市'}, {id: 405, name: '邵阳市'} ] break default: break } res.json(cityList) }) ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值