Node.js将文件发送到客户端

Mar*_*aev 5 html javascript node.js

您好,我一直在尝试从node.js向客户端发送文件.我的代码可以工作,但是当客户端转到指定的url(/helloworld/hello.js/test)时,它会传输文件.从谷歌浏览器访问它使文件(.mp3)在播放器中播放.

我的目标是让客户端的浏览器下载文件并询问客户端他想要存储它的位置,而不是在网站上传输它.

http.createServer(function(req, res) {
    switch (req.url) {
        case '/helloworld/hello.js/test':

            var filePath = path.join(__dirname, '/files/output.mp3');
            var stat = fileSystem.statSync(filePath);

            res.writeHead(200, {
                'Content-Type': 'audio/mpeg',
                'Content-Length': stat.size
            });

            var readStream = fileSystem.createReadStream(filePath);
            // We replaced all the event handlers with a simple call to readStream.pipe()
            readStream.on('open', function() {
                // This just pipes the read stream to the response object (which goes to the client)
                readStream.pipe(res);
            });

            readStream.on('error', function(err) {
                res.end(err);
            });
    }
});
Run Code Online (Sandbox Code Playgroud)

Hüs*_*BAL 14

你需要设置一些标题标志;

res.writeHead(200, {
    'Content-Type': 'audio/mpeg',
    'Content-Length': stat.size,
    'Content-Disposition': 'attachment; filename=your_file_name'
});
Run Code Online (Sandbox Code Playgroud)

用下载取代流媒体;

var file = fs.readFile(filePath, 'binary');

res.setHeader('Content-Length', stat.size);
res.setHeader('Content-Type', 'audio/mpeg');
res.setHeader('Content-Disposition', 'attachment; filename=your_file_name');
res.write(file, 'binary');
res.end();
Run Code Online (Sandbox Code Playgroud)

  • 由于Node.js是单线程的,因此请求处理程序中的用户`readFileSync`非常糟糕.因此,如果您对该URL有两个请求,则第二个请求将等到第一个完成它的操作.在localhost上你可能没有注意到任何错误,但在每秒有1,000个请求的生产服务器上会有延迟.使用[`readFile`](http://nodejs.org/api/fs.html#fs_fs_readfile_filename_options_callback)代替回调 (6认同)

Ren*_*abu 8

以下解决方案适用于 Express JS。

app.get('/download', (req, res) => res.download('./file.pdf'))
Run Code Online (Sandbox Code Playgroud)

  • 为什么这被否决了?我刚刚对此进行了测试,它似乎在 Node Express 服务器上工作得很好。如果这个答案有问题,请提供反馈,以便每个人都知道为什么不应该使用它。 (2认同)
  • 可能是因为问题不是要求 Express? (2认同)