如何从节点触发浏览器下载.JS套接字流



我的node.js应用程序通过var socket = net.createConnection(port, ip);连接,从另一台服务器下载文件。一旦建立连接,服务器就会将文件作为数据发送。

然后我通过捕捉到它

socket.on('data', function(data) {
}).on('connect', function() {
}).on('end', function() {
console.log('DONE');
});

我最初的目标是,使用上面的方法下载文件,同时将字节作为可下载文件提供给客户端的浏览器。例如:用户点击网站上的一个按钮,该按钮会触发服务器端下载功能,用户会收到文件保存提示。节点。JS然后从远程服务器下载文件,同时在浏览器客户端将每个新字节提供给用户。这可能吗?我想它需要发送八位字节流的头来触发浏览器节点之间的文件传输。JS。但是怎么做呢?

更新

现在我在下面的答案的帮助下尝试了下面的代码:

app.get('/download', function (req, res) {
res.setHeader('Content-disposition', 'attachment; filename=' + "afile.txt");
res.setHeader('Content-Length', "12468")
var socket = net.createConnection(1024, "localhost");
console.log('Socket created.');
socket.on('data', function(data) {
socket.pipe(res)
}).on('connect', function() {
// // Manually write an HTTP request.
// socket.write("GET / HTTP/1.0rnrn");
}).on('end', function() {
console.log('DONE');
socket.end();
});
});

数据被作为下载发送到用户的浏览器,但最终结果是一个损坏的文件。我检查了里面的内容,发现在这个过程中有什么东西导致文件损坏。我想现在我必须逐字节写?而不是做插座管?

您需要在http响应中设置内容处理标头:

response.writeHead(200, {
'Content-Disposition': 'attachment; filename=genome.jpeg; modification-date="Wed, 12 Feb 1997 16:29:51 -0500"'
});
yourDataStream.pipe(response);

参见RFC2183

看起来你可能想要这个:

app.get('/download', function (req, res) {
res.attachment('afile.txt');
require('http').get('http://localhost:1234/', function(response) {
response.pipe(res);
}).on('error', function(err) {
res.send(500, err.message);
});
});

我找到了解决方案!通过执行res.write(d),我能够将来自其他连接的字节引导到用户浏览器下载。

app.get('/download', function (req, res) {
res.setHeader('Content-disposition', 'attachment; filename=' + "afile.jpg");
res.setHeader('Content-Length', "383790");
res.setHeader('Content-Type','image/jpeg');
var socket = net.createConnection(1024, "localhost");
console.log('Socket created.');
//socket.setEncoding("utf8");
socket.on('data', function(d) {
console.log(d);
res.write(d);
}).on('connect', function() {
// // Manually write an HTTP request.
// socket.write("GET / HTTP/1.0rnrn");
}).on('end', function() {
console.log('DONE');
socket.end();
});

});

最新更新