关于javascript:下载文件功能

3次阅读

共计 1017 个字符,预计需要花费 3 分钟才能阅读完成。

用 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);
      }
    },
正文完
 0