前端文件下载方法合集

222 阅读1分钟

1.frame标签-js

const downloadFile = (url) => {
  const frame = document.createElement(`iframe`)
  frame.src = url
  frame.style.display = `none`
  document.body.appendChild(frame)
  setTimeout(function () {
    frame.remove()
  }, 5 * 60 * 1000)
}

2.a标签-html

    <a
      :href="url"
      target="_blank"
    >
      下载
    </a>

3.a标签-js

    let fileUrl = ''//下载地址
    let aLink = document.createElement('a')
    aLink.style.display = 'none'
    aLink.href = fileUrl
    aLink.setAttribute('download', fileName)//自定义文件名
    document.body.appendChild(aLink)
    aLink.click()
    document.body.removeChild(aLink)//移除标签

4.调用接口-blob

const instance = axios.create({
    baseURL: "http://192.168.43.55:8000",
    timeout: 5000,
    responseType: 'blob'  // 这个不设置会导致接受的文件流能下载但无法打开,设置后后端返回的文件流会自动保存在返回信息的data中
});

// url: 后端接口地址 param: 所需参数
this.axios.post(url, param).then(res => {  // res保存的是接口的一些信息包括状态码status,config,data等一些信息,文件流默认存在data中
        let blob = new Blob([res.data]);
        let blobUrl = window.URL.createObjectURL(blob);
        // 转换完成就跟第一种情况一致,通过a链接下载
        let aLink = document.createElement('a');
        aLink.style.display = 'none';
        aLink.href = blobUrl;
        aLink.setAttribute('download', fileName) 
        document.body.appendChild(aLink);
        aLink.click(); 
        document.body.removeChild(aLink);
        window.URL.revokeObjectURL(blobUrl) // 前面创建的url地址最后也要去掉,为了安全和性能

    })
    .catch(e => console.log(e))

导出excel格式: new Blob([res], {type: 'application/vnd.ms-excel'})
导出word格式:  new Blob([res], {type: 'application/msword'})
导出.zip格式:  new Blob([res], {type: 'application/zip'})
导出.xls或者.xlsx  new Blob([res], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'})