简体   繁体   English

从Node.js中的URL读取图像

[英]Reading a image from url in nodejs

我想从url读取图像并将其存储在mongo db中。我基本上已经读取了字符串值并完成了上述过程。但是由于如何读取图像而陷入困境,对此的任何想法都将非常有帮助。

Tested with node 0.8.8 and mongojs . 使用节点0.8.8和mongojs进行了测试。

var http = require("http");
var mjs = require("mongojs");

// url of the image to save to mongo
var image_url = "http://i.imgur.com/5ToTZky.jpg";

var save_to_db = function(type, image) {

   // connect to database and use the "test" collection
   var db = mjs.connect("mongodb://localhost:27017/database", ["test"]);

   // insert object into collection 
   db.test.insert({ type: type, image: image }, function() {
      db.close();
   });

};

http.get(image_url, function(res) {

   var buffers = [];
   var length = 0;

   res.on("data", function(chunk) {

      // store each block of data
      length += chunk.length;
      buffers.push(chunk);

   });

   res.on("end", function() {

      // combine the binary data into single buffer
      var image = Buffer.concat(buffers);

      // determine the type of the image
      // with image/jpeg being the default
      var type = 'image/jpeg';
      if (res.headers['content-type'] !== undefined)
         type = res.headers['content-type'];

      save_to_db(type, image);

   });

});

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

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