下载文件乱码问题

256 阅读1分钟

下载文件乱码问题解决方案

在请求时加上responseType: 'blob', 接收返回的blob类型 转换文件流

blobToFile (fileName, b, isUtf8) {
    if (isUtf8 === true) {
      b = '\uFEFF' + b
    }

    const blob = new Blob([b])
    if ('download' in document.createElement('a')) { // 非IE下载
      const elink = document.createElement('a')
      elink.download = fileName
      elink.style.display = 'none'
      if (isUtf8 === true) {
        elink.href = URL.createObjectURL(blob, { type: 'text/csv;charset=utf-8' })
      } else {
        elink.href = URL.createObjectURL(blob)
      }

      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href) // 释放URL 对象
      document.body.removeChild(elink)
    } else { // IE10+下载
      navigator.msSaveBlob(blob, fileName)
    }
  },
  //下载文件错误提示文件下载
  downByUrl (url, fileName) {
    if ('download' in document.createElement('a')) { // 非IE下载
      const elink = document.createElement('a')
      elink.download = fileName
      elink.style.display = 'none'
      elink.href = url
      document.body.appendChild(elink)
      elink.click()
      document.body.removeChild(elink)
    }
  }