4从服务器下载文件

点击按钮发送请求,服务器返回一个文件。如何保存这个文件的问题
通过a标签直接定位到服务器上的文件原则上也是可以的

1.使用Axios封装的请求函数
// request是一个axios实例,返回一个promise
export function getConfigFile(){
  return request({
    url: "cgi-bin/configfile"
    method: "get",
    // 需要设置responseType
    responseType: "blob"
  })
}
2.点击按钮,触发时间,调用函数发送请求下载文件
// 按钮绑定的函数为downloadFile
function downloadFile(){
  getConfigFile().then(res => {
    // 获取到文件名(文件名放在请求头中)
    let file_name = res.headers['content-disposition'].split("=")[1]
    // 获取到文件
    let file = res.data
    
    // 通过blob保存
    const blob = new Blob([file])
    if('download' in document.createElement("a")){
      // 非IE下载
      const elink = document.createElement("a")
      elink.download = file_name
      elink.style.display = "none"
      // 表示一个指定的File对象或Bolob对象
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href)
      document.body.removeChild(elink)
    }else{
      // IE10+下载
      navigator.msSaveBlo(blob, file_name)
    }
  }).catch(err => {
    console.log("请求文件失败!")
  })
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容