Ajax 响应是文件下载
Ajax response is a file download
我正在使用 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()
中启动下载?
理想情况下我根本不想处理响应并直接启动下载。
响应 headers 看起来(如预期的那样):
Content-disposition: attachment; filename=test.zip
Connection: keep-alive
Transfer-Encoding: chunked
Content-type: application/zip
如果您以八位字节流的形式返回文件数据,则可以像此处那样启动下载 -> Save file Javascript with file name
uriContent = "data:application/octet-stream," + encodeURIComponent(dataFromServer);
newWindow=window.open(uriContent, 'filename.txt');
我正在使用 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()
中启动下载?
理想情况下我根本不想处理响应并直接启动下载。
响应 headers 看起来(如预期的那样):
Content-disposition: attachment; filename=test.zip
Connection: keep-alive
Transfer-Encoding: chunked
Content-type: application/zip
如果您以八位字节流的形式返回文件数据,则可以像此处那样启动下载 -> Save file Javascript with file name
uriContent = "data:application/octet-stream," + encodeURIComponent(dataFromServer);
newWindow=window.open(uriContent, 'filename.txt');