繁体   English   中英

我正在尝试从其他服务器读取图像并在响应中写入

[英]I am trying to read image from different server and write on response

function media(req,res){
  console.log(req.query.image);
  var collectionName = 'imageTable';

      var selector = MongoHelper.idSelector(req.query.image);
      MongoHelper.findOne(selector, collectionName, function(err, image) { 
          console.log(image.picture);
          var url_parts = url.parse(image.picture);

          var options = {host: url_parts.hostname, path: url_parts.pathname};

          http.get(options).on('response', function (response) {
            var body = '';
            var i = 0;
            response.on('data', function (chunk) {
                i++;
                body += chunk;
                console.log('BODY Part: ' + i);
            });
            response.on('end', function () {

            console.log('Finished');
            res.writeHead(200,{'Content-Type':'image/JPEG'});
            res.write(body);
            res.end(); 
        });
        });
      });
}

我正在从其他服务器获取图像。 我有该图片的网址。 我正在写回应。 但是,此处的响应图像已损坏。 关于如何写jpeg图片作为响应的任何想法吗?

function media(req,res){
  console.log(req.query.image);
  var collectionName = 'facebook';

      var selector = MongoHelper.idSelector(req.query.image);
      MongoHelper.findOne(selector, collectionName, function(err, image) {

          var url_parts = url.parse(image.picture);
          var options = {host: url_parts.hostname, path: url_parts.pathname};

          http.get(options).on('response', function (response) {
            res.writeHead(200,{'Content-Type':'image/JPEG'});
            response.on('data', function (chunk) {
                res.write(chunk);
            });
            response.on('end', function () {
            res.end(); 
        });
        });
      });
}

在这里,我得到了解决方案。 而不是最后写入整个数据。 每次获取时都编写它,并在到达文件末尾时结束响应。 但是,如果有人有更好的主意可以在这里写。

暂无
暂无

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

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