js导出文件

2024-02-29 javascript 文件 导出

总结了自己工作中罕用的三种导出文件的形式

  • 后端返回的单个链接下载
function download(url, filename) {
  let link = document.createElement("a")
  link.style.display = "none"
  link.href = `${url}`
  link.setAttribute("download", `${filename}`)
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  link = null
}
  • 后端返回多个链接,批量下载
function batchDownload(data) {
  data.forEach(item => {
    download(item.filePath, item.fileName)
  })
}
  • 后端返回一个流文件
function downloadFileStream(name = "1", content, suffix = "doc") {
  //文件流文件下载
  const blob = new Blob([content])
  const fileName = `${name}.${suffix}`
  const elink = document.createElement("a")
  elink.download = fileName
  elink.style.display = "none"
  elink.href = URL.createObjectURL(blob)
  document.body.appendChild(elink)
  elink.click()
  URL.revokeObjectURL(elink.href) // 开释URL 对象
  document.body.removeChild(elink)
}

相关文章