简体   繁体   English

Node.js 向客户端发送文件

[英]Node.js send file to client

Hello there I have been trying to send a file from node.js to the client.您好,我一直在尝试将文件从 node.js 发送到客户端。

My code works however when the client goes to the specified url ( /helloworld/hello.js/test ) it streams the file.但是,当客户端转到指定的 url ( /helloworld/hello.js/test ) 时,我的代码会工作,它会流式传输文件。

Accessing it from Google Chrome makes the file (.mp3) play in a player.从 Google Chrome 访问它会使文件 (.mp3) 在播放器中播放。

My goal is to have the client's browser download the file and ask the client where he wants to store it, not stream it on the website.我的目标是让客户端的浏览器下载文件并询问客户端他想在哪里存储它,而不是在网站上流式传输它。

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);
            });
    }
});

You need to set some header flags;您需要设置一些标题标志;

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

For replacing streaming with download;用下载代替流媒体;

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();

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

app.get('/download', (req, res) => res.download('./file.pdf'))
response.writeHead(200, {
    'Content-Type': 'audio/mpeg',
     modification-date="date_object",
    'Content-Disposition: attachment; 
     filename=output.mp3' 

  });

you need to works on your header part ie your content-Disposition part, only then it will allow you to get the data out.你需要工作在你的头部分,即您的内容部署的一部分,只有这样它可以让你获取数据了。 read more about content Disposition阅读更多关于内容处置

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM