js发送文件给客户端

js发送文件给客户端

本文介绍了Node.js发送文件给客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我一直在试图从node.js发送一个文件给客户端。我的代码工作,但是当客户端去指定的网址(/helloworld/hello.js/test)它流文件。从谷歌浏览器访问它使文件(.mp3)在播放器中播放。

Hello there I have been trying 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 streams the file. Accessing it from google chrome make the file (.mp3) play in a player.

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

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

这篇关于Node.js发送文件给客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 12:38