前端实现文件在线预览txt,pdf,doc,xls,ppt几种格式

时间:2022-02-26 04:30:48

做法就是使用iframe标签

1.text,pdf的文件预览

<iframe class="filename" :src="文件的地址" width='100%' height='600' frameborder='1' ></iframe>

2.doc,xls,ppt等office的预览

<iframe class="filename"  :src="https://view.officeapps.live.com/op/view.aspx?src=后面是文件的地址" width='100%' height='600' frameborder='1' ></iframe>

3.我们可以看出,差别只有src的属性,所以要设置文件预览同时可以满足txt,pdf,和office类型格式的文件,只需要配置src就可以,根据文件后缀判断如果是office的类型就在url前加上

https://view.officeapps.live.com/op/view.aspx?src=
for (let i=0;i<this.data.quoteInfo.goodsList.length;i++) {
for(let j=0;j<this.data.quoteInfo.goodsList[i].goodsAttachments.fileAttachmentList.length;j++){
let value = this.data.quoteInfo.goodsList[i].goodsAttachments.fileAttachmentList[j]
let valueFormat = value.name.substring(value.name.lastIndexOf('.') + 1)//前面逻辑不用看,至此拿到文件后缀
if(valueFormat=='doc'|| valueFormat=='docx'|| valueFormat=='xls' || valueFormat=='xlsx') {//根据后缀判断如果是office格式的,做路径的拼接,拼接微软在线预览地址即可
要预览的文件地址='https://view.officeapps.live.com/op/view.aspx?src='+要预览的文件地址
}
}
}

4.iframe 的宽高边框都是可配的,:width=宽的变量;:height=高的变量;:frameborder=边框的变量,no则是无边框

这些格式之外的文件没有办法预览如RAR,ZIP,会直接提醒你下载,基本完成预览的需求,重点就是预览文件前,把office文件的路径配置下,使用微软提供的在线office预览