vue+elementUI下载文件、截取url后缀

一、函数代码

 1 downloadReport(url) {
 2       // 从url中找到文件名的索引位置
 3       const index = url.lastIndexOf('/') + 1
 4       // 匹配url后缀,检查是否为pdf,是则窗口打开,否则下载到本地
 5       if (url.lastIndexOf('.pdf') === -1) {
 6         // 创建下载
 7         const link = document.createElement('a')
 8         link.style.display = 'none'
 9         link.href = url
10         link.download = url.substring(index)
11         link.click()
12         this.$message({
13           message: `正在下载,请稍后在本地查看`,
14           type: 'success'
15         })
16       } else {
17         window.open(url, url.substring(index))
18       }
19     }

二、函数说明

indexOf('xxx'): 由左至右,查找某指定字符串在完整字符串中首次出现的位置索引。
lastIndexOf('xxx'): 由右至左,查找某指定字符串在完整字符串中首次出现的位置索引。
substring(startIndex, endIndex): 截取字符串从索引startIndex到endIndex间的字符,end为可选参数,不填意味着截取从startIndex到url.length-1位置的字符串。
posted @ 2020-12-28 10:12  爱就码上行动  阅读(3235)  评论(0编辑  收藏  举报