【问题标题】:Ajax response is a file downloadAjax响应是一个文件下载
【发布时间】:2015-11-04 17:15:32
【问题描述】:

我正在使用 Polymer 的 iron-ajax 元素向服务器端点发送 XMLHTTPRequest:

 <iron-ajax
  id="ajax"
  method="POST"
  url="/export/"
  params=''
  handle-as="json"
  on-response="handleResponse"
</iron-ajax>

我的 Koa/Express-server 响应如下读取流:

router.post('/export' , function*(){

  var file = __dirname + '/test.zip';
  var filename = path.basename(file);
  var mimetype = mime.lookup(file);

  this.set('Content-disposition', 'attachment; filename=' + filename);
  this.set('Content-type', mimetype);
  this.body = fs.createReadStream(file);
})

如何在handleResponse() 中启动下载? 理想情况下,我根本不想处理响应并直接启动下载。

响应标头看起来(如预期)如下:

Content-disposition: attachment; filename=test.zip
Connection: keep-alive
Transfer-Encoding: chunked
Content-type: application/zip

【问题讨论】:

    标签: javascript ajax express polymer koa


    【解决方案1】:

    如果您将文件数据作为八位字节流返回,您可以像在此处完成的那样启动下载 -> Save file Javascript with file name

    uriContent = "data:application/octet-stream," + encodeURIComponent(dataFromServer);
    
    newWindow=window.open(uriContent, 'filename.txt');
    

    【讨论】:

      猜你喜欢
      • 2016-11-26
      • 2019-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-20
      • 2020-08-27
      • 1970-01-01
      • 2021-08-03
      相关资源
      最近更新 更多