zoukankan      html  css  js  c++  java
  • vue+axios下载文件的实现

    HTML代码: <el-button size="medium" @click="download">下载表格</el-button>

    js代码:

    <script>

     import fileDownload from 'js-file-download' //下载js-file-download:npm install js-file-download
    methods: {
        //下载表格
        downloadHttpRequest(u, json, success, fail) {
          this.$http({
            method: "post",
            url: u,
            data: json,
            headers: {
              "Content-type": "application/json",
              "Access-Control-Allow-Methods": "*",
              "Access-Control-Allow-Origin": "*",
              "Access-Control-Allow-Headers": ["x-requested-with", "content-type"]
            },
            responseType: "blob"
          })
            .then(res => 
            {
                let resBlob = res.data // <--- store the blob if it is
                let resData = null
                let filename = 'attach.txt';  //给下载文件命名
                try {
                let resText =  new Promise((resolve, reject) => {
                    let reader = new FileReader()
                    reader.addEventListener('abort', reject)
                    reader.addEventListener('error', reject)
                    reader.addEventListener('loadend', () => {
                    resolve(reader.result)
                    })
                    reader.readAsText(resBlob)
                })
                resData = JSON.parse(resText) // <--- try to parse as json evantually
                } catch (err) {
                // ignore
                }
                if (resData) {
                    if (resData.error) {
                        // handle error
                    } else {
                        // handle data
                    }
                } else {
                // handle blob
                fileDownload(resBlob, filename)
                }
            });
        },
        download() {
          let _this = this;
          //下载表格接口/passport/getPassportNumberAndCode
          _this.downloadHttpRequest(
            "/ARPassport/passport/getPassportNumberAndCode",
            {
              code: 0,
              data: _this.$route.query.id
            },
            function success(res) {
            },
            function fail(err) {
            }
          );
        }
    }    
    </script>

    此方法参考了网上的资料

  • 相关阅读:
    Web 请求响应原理(转)
    openstack中的floating ip与阿里云的公网ip
    一起来说 Vim 语
    vsftpd.conf 详解与实例配置
    jquery 放大图片
    jQuery 之 .stop() 方法
    jquery 插件开发
    jquery 之效果
    jquery 之事件 多库共存(noConflict)
    测试网站是共享还是独立ip
  • 原文地址:https://www.cnblogs.com/hj0711/p/9104002.html
Copyright © 2011-2022 走看看