文件下载

2024-04-06 21:54:54

阅读:242
分类:代码段
标签:htmljs

文件下载

  1. a 标签直接下载
  <a href="/xxx.txt" download="自定义文件名">点击下载</a>
  1. 前端 ajax 请求返回 blob
  // File对象的应用
  new File(bits, name[, options])
  // bits 数组项支持 ArrayBuffer ArrayBufferView Blob DOMString
  // name 文件名或者路径
  // options 一个对象 {type,lastModified} type文件mime类型 lastModified最后修改时间

  // 以下载excel为例
  const exportfiles = async (url, params) => {
    const fileRes = await window.fetch(
      url, 
      { 
        headers: { 'Content-Type': 'application/json', }
        method: 'POST',
        body: JSON.stringify({params: '参数'})
      }
    )
    const buffer = await fileRes.blob()

    const fileUrl = URL.createObjectURL(new File([buffer], 'excel.xls', {type: 'application/vnd.ms-excel'}))

    const a = document.createElement('a')
    a.href = fileUrl.toString()
    a.download = this.title
    a.click()
  }
  // 调用
  exportfiles(url, params)

评论:

    X

    备案号 皖ICP备19021899号-1  技术支持 © 947968273@qq.com