2019-12-16-vue-ajax-原生下载文件

vue-ajax 原生下载文件

<template>
    <div>
    </div>
</template>
<script>
export default {
  data() {
    return {};
  },
  methods: {
    downLoad () {
      let url = 'localhost:8000/download'
      let xhr = new XMLHttpRequest()
      xhr.open('get', url, true)
      xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded') // 设置请求头 open后添加
      xhr.setRequestHeader('X-token', 'cdksnjfdhscibdsfgehdslkc') // 带上token
      xhr.responseType = 'blob' // 返回类型blod    blob 存储着大量二进制数据
      /** +++++
        xhr.onreadystatechange = function () {
          if (xhr.readyState==4 && xhr.status==200) {
              ...
      }
      ++++ **/
      
      xhr.onload = function () {
          if (this.status === 200) {  // this  指 xhr对象
            let blob = this.response 
            let reader = new FileReader()
            reader.readAsDateURL(blob)  // 转换为base64, 可直接放进a标签的href
            reader.onload = functions(e) {
                let a = document.createElement('a') // 创建一个a标签用于下载
                a.download = '文件名和格式.text'
                a.href = window.URL.createObjectURL(blob)
                a.click()
            }
          }
      }
    }
   
  }
};
</script>
<style scoped>

</style>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容