【问题标题】:Node.js send file to clientNode.js 向客户端发送文件
【发布时间】:2014-03-01 22:34:29
【问题描述】:

您好,我一直在尝试将文件从 node.js 发送到客户端。

我的代码可以工作,但是当客户端转到指定的 url (/helloworld/hello.js/test) 时,它会流式传输文件。

从 Google Chrome 访问它会使文件 (.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);
            });
    }
});

【问题讨论】:

    标签: javascript html node.js


    【解决方案1】:

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

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

    用下载代替流式传输;

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

    【讨论】:

    • 感谢它的工作,但现在它只下载文件的 4mb 现在整个文件大约 6mb。
    • 你检查过文件内容了吗?一切都在里面?
    • 由于 Node.js 是单线程的,因此请求处理程序中的用户 readFileSync 非常糟糕。因此,如果您对该 url 有两个请求,第二个请求将等到第一个请求完成它的操作。在 localhost 上,您可能不会注意到有任何问题,但在每秒 1,000 个请求的生产服务器上会出现延迟。将readFile 与回调一起使用
    • 感谢@Zub 的警告。这只是一个例子,但你是绝对正确的。所以,我更新了我的代码只是为了防止你描述的这种情况
    • 可以改用res.download()吗?
    【解决方案2】:
    response.writeHead(200, {
        'Content-Type': 'audio/mpeg',
         modification-date="date_object",
        'Content-Disposition: attachment; 
         filename=output.mp3' 
    
      });
    

    您需要处理您的标题部分,即您的内容处置部分,只有这样它才能让您获取数据。阅读更多关于content Disposition

    【讨论】:

    • @MaratArguinbaev - 你在这方面取得了任何进展并让它发挥作用吗?我知道它是一个旧线程,但我正在尝试做类似的事情。 Qnother 问题是你是坚持使用 NODE.js 还是最终转向另一个 websockets 框架/解决方案?谢谢!
    【解决方案3】:

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

    app.get('/download', (req, res) => res.download('./file.pdf'))
    

    【讨论】:

    • 为什么会被否决?我刚刚对此进行了测试,它似乎适用于 Node Express 服务器。如果此答案有问题,请提供反馈,以便每个人都知道为什么不应该使用它。
    • @StevenVerheyen :这可行,但不知何故有人否决了它。不知道为什么
    • 是的,它有效,谢谢哥们,这是reference
    • 可能是因为问题不是要 Express 的?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-01
    • 2017-05-07
    • 1970-01-01
    • 1970-01-01
    • 2012-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多