将文本作为下载文件发送

Send text as a download file

正在尝试将简单的文本字符串作为文件发送,该文件将根据请求以特定名称下载。似乎无法弄清楚为什么此代码会失败。

var text_ready = "This is a content of a txt file."
res.setHeader('Content-type', "application/octet-stream");
res.setHeader('Content-disposition', 'attachment; filename=file.txt');
res.send( new Buffer(text_ready) );

执行此代码时,我只收到一个 XHR 响应(以该字符串作为内容),但没有启动下载。但我预计收到此响应将强制浏览器下载一个文件,名称为 file.txt,其内容为上述字符串。

如何解决?我做错了什么?

也许这很重要:在 Chrome 41 Windows 下工作。

EDIT: 看来我得描述得更深一点了。工作流程如下:

测试

  1. 工作 当我 导航 通过输入这个 url 手动到那个 url 到地址栏和按回车
  2. 不起作用当我用鼠标单击那个单元格时-发送了请求,收到了响应但没有下载已启动。

在我的 node.js 版本 0.12.2、Windows 7、Chrome 和 Firefox

上测试
var http = require('http');

http.createServer(function (req, res) {
var text_ready = "This is a content of a txt file."


res.writeHead(200, {'Content-Type': 'application/force-download','Content-disposition':'attachment; filename=file.txt'});

res.end( text_ready );
}).listen(8080, '127.0.0.1');
console.log('Server running at http://127.0.0.1:8080/');

我认为您不是 运行 最新版本的 node.js。也许您只能更改 Content-type header,这可能会起作用。此外,您可以使用 res.end( new Buffer(text_ready) );。我已经测试过了。

已编辑: 如何使用 javascript(jQuery onclick) 调用从 node.js 下载文件:

Javascript:

<script type="text/javascript">
$(document).ready(function(){
    $("#button").on('click',function(){
        window.location = 'http://127.0.0.1:1337/';
    });
});
</script>

HTML:

<button id="button">Download</button>

我相信您知道如何将 jQuery 重写为 angularJS。 :) 我认为这比使用 Ajax 调用更好。如果你真的需要Ajax,我会告诉你怎么做。