vue 打开浏览器新标签页预览 pdf 和 txt 文档,以及新标签页标题修改

发布时间 2023-07-12 16:06:09作者: dirgo
 1 // 在线查看
 2     showOnline({ id, fileExt, fileName }) {
 3       if (fileExt && ['jpg', 'jpeg', 'gif', 'bmp', 'png'].includes(fileExt.toLowerCase())) {
 4         download(`/file-item/${id}/download`)
 5           .then(result => {
 6             const blob = new Blob([result.data], { type: 'application/x-msdownload' })
 7             this.imageUrl = URL.createObjectURL(blob)
 8           })
 9         this.dialogVisible = true
10       } else if (fileExt && fileExt.toLowerCase() === 'pdf') {
11         download(`/file-item/${id}/download`)
12           .then(result => {
13             const blob = new Blob([result.data], { type: 'application/pdf' })
14             const url = URL.createObjectURL(blob)
15             const page = window.open(url, '_blank')
16             setTimeout(function() { page.document.title = fileName }, 100)
17           })
18       } else if (fileExt && fileExt.toLowerCase() === 'txt') {
19         download(`/file-item/${id}/download`)
20           .then(result => {
21             // 注意type,不同类型文件,type不同;另外text 第一个参数的数组第一项加'\ufeff',设置编码,解决中文乱码
22             const blob = new Blob(['\ufeff', result.data], { type: 'text/plain' })
23             const url = URL.createObjectURL(blob)
24             const page = window.open(url, '_blank')
25             // page.document.title = '新的标题名'
26             // 因为window.open 异步,上面的方法很多时候不起效,加延时
27             setTimeout(function() { page.document.title = fileName }, 100)
28           })
29       } else {
30         this.$utils.message('info', '此类型文件不支持预览,请下载查看!')
31       }
32     }

主要就是用window.open()方法,注意事项都在上面代码中

参考文章:

https://www.cnblogs.com/cbxg24543/p/15589287.html

https://juejin.cn/post/7024133497958694925

https://www.cnblogs.com/weiliang-song/p/16085957.html