h5中文件下载

347 阅读1分钟

封装一个单独的js,用来实现将请求结果转成二进制文件流的形式,来触发浏览器自身的下载功能。

module.exports = function (blob, filename, mime) {
  // var blob = new Blob(blob, {type: mime || 'application/octet-stream'})
  if (typeof window.navigator.msSaveBlob !== 'undefined') {
    // IE workaround for "HTML7007: One or more blob URLs were
    // revoked by closing the blob for which they were created.
    // These URLs will no longer resolve as the data backing
    // the URL has been freed."
    window.navigator.msSaveBlob(blob, filename)
  } else {
    let blobURL = window.URL.createObjectURL(blob)
    let tempLink = document.createElement('a')
    tempLink.style.display = 'none'
    tempLink.href = blobURL
    tempLink.setAttribute('download', filename)
    tempLink.setAttribute('target', '_blank')
    document.body.appendChild(tempLink)
    tempLink.click()
    document.body.removeChild(tempLink)
    window.URL.revokeObjectURL(blobURL)
  }
}

具体实现

axios.get(obj.dataUrl, {responseType: 'blob'}).then(res => {
    fileDownload(res.data, obj.dataName)
})