Node.js send file to client

Hello, I tried to send a file from node.js to the client.

My code works, however, when the client goes to the specified URL ( /helloworld/hello.js/test), it transfers the file.

Access to it from Google Chrome makes the file (.mp3) play in the player.

My goal is to get the client browser to download the file and ask the client where he wants to save it, and not transfer it to 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);
            });
    }
});
+5
source share
2 answers

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

To replace 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();
+14
source
response.writeHead(200, {
    'Content-Type': 'audio/mpeg',
     modification-date="date_object",
    'Content-Disposition: attachment; 
     filename=output.mp3' 

  });

, .. - Disposition, . content Disposition

-1

All Articles