Ajax响应是文件下载

时间:2015-11-04 17:15:32

标签: javascript ajax express polymer koa

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

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

我的Koa / Express服务器使用如下读取流进行响应:

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

1 个答案:

答案 0 :(得分:2)

如果您将文件数据作为八位字节流返回,则可以启动下载,例如此处完成 - &gt; Save file Javascript with file name

uriContent = "data:application/octet-stream," + encodeURIComponent(dataFromServer);

newWindow=window.open(uriContent, 'filename.txt');