4

我使用此代码将图像传送给我的客户:

req.pipe(fs.createReadStream(__dirname+'/imgen/cached_images/' + link).pipe(res))

确实有效,但有时图像未完全传输。但是在客户端(浏览器)和服务器端(node.js)都不会抛出错误。

我的第二次尝试是

var img = fs.readFileSync(__dirname+'/imgen/cached_images/' + link);
res.writeHead(200, {
  'Content-Type' : 'image/png'
});
res.end(img, 'binary');

但它会导致同样的奇怪行为......

有人对我有线索吗?

(抽象代码...)

var http = require('http');
http.createServer(function (req, res) {
    Imgen.generateNew(
        'virtualtwins/www_leonardocampus_de/overview/28',
        'www.leonardocampus.de',
        'overview',
        '28',
        null,
        [],
        [],
        function (link) {
          fs.stat(__dirname+'/imgen/cached_images/' + link, function(err, file_info) {
                if (err) { console.log('err', err); }
                  console.log('file info', file_info.size);
                  res.writeHead(200, 'image/png');
                  fs.createReadStream(__dirname+'/imgen/cached_images/' + link).pipe(res);
              });
        }
        );
}).listen(13337, '127.0.0.1');

Imgen.generateNew只需创建一个新文件,将其保存到磁盘并返回路径(链接)。

4

2 回答 2

2

What the problem was: I had 2 different writeStreams! If WriteStream#1 is closed, the second should be closed too and then it all should be piped.

But node is asynchronous so while one has been closed, the other one hasn't. Even the stream.end() was called... well you always should wait for the close event!

于 2014-04-26T11:44:55.543 回答
2

我以前用过这个,所需要的只是在function (req, res) {

var path = ...; 
res.writeHead(200, {
  'Content-Type' : 'image/png'
});
fs.createReadStream(path).pipe(res);

wherepath是要发送的文件的计算路径。.pipe()将数据从读流传输到写流,在读流结束时调用end,所以不需要使用res.end()after。

于 2012-07-11T08:09:38.847 回答