关于javascript:下载文件功能

用a标签的download下载,如果是第三方资源的话,就须要申请回来,否则的话,就会被当做链接关上。还要看看后端有没有CORS策略阻止。

//判断是不是ie浏览器
   IEVersion() {
      let userAgent = navigator.userAgent; //获得浏览器的userAgent字符串  
      let isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; //判断是否IE<11浏览器  
      let isEdge = userAgent.indexOf("Edge") > -1 && !isIE; //判断是否IE的Edge浏览器  
      let isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1;
      if(isIE || isEdge || isIE11) {
        return true
      }
    },
 download(){
      const fileName = 'ITSell.jpeg' // 导出文件名
      // 对于<a>标签,只有 Firefox 和 Chrome(内核) 反对 download 属性
      // IE10以上反对blob然而仍然不反对download
     
        const blob = new Blob([content]) // 结构一个blob对象来解决数据。content是申请返回的blob数据;申请的时候,要加上responseType = 'blob'让服务器返回blob类型
      if ('download' in document.createElement('a') && !IEVersion()) { // 反对a标签download的浏览器
        const link = document.createElement('a') // 创立a标签
        link.download = fileName // a标签增加属性
        link.style.display = 'none'
        link.href =URL.createObjectURL(blob);
        document.body.appendChild(link)
        link.click() // 执行下载
        URL.revokeObjectURL(link.href) // 开释url
        document.body.removeChild(link) // 开释标签
      } else { // 其余浏览器
        navigator.msSaveBlob(blob, fileName);
      }
    },

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理