javascript - Reading a image from url in nodejs - Stack Overflow

I want to read a image from a url and store it in mongo db.I have basically read string values and done

I want to read a image from a url and store it in mongo db.I have basically read string values and done the above procedure.But am stuck as how to read a image.Any idea on that will be really helpful.

I want to read a image from a url and store it in mongo db.I have basically read string values and done the above procedure.But am stuck as how to read a image.Any idea on that will be really helpful.

Share Improve this question asked Feb 28, 2013 at 7:01 Amanda GAmanda G 1,99111 gold badges33 silver badges44 bronze badges 3
  • Do you need help with downloading the image or storing it, or both? – diolemo Commented Feb 28, 2013 at 7:07
  • simply request to download the img and write to file system – williamC Commented Feb 28, 2013 at 7:11
  • for example if i have a url as localhost:1340/promotionDetails?promotion_id=PROM008765 I read the promotion_id using the express module as req.id.Can i do the same for image ? – Amanda G Commented Feb 28, 2013 at 7:17
Add a ment  | 

1 Answer 1

Reset to default 6

Tested with node 0.8.8 and mongojs.

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

// url of the image to save to mongo
var image_url = "http://i.imgur./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() {

      // bine 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);

   });

});

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745228246a4617562.html

相关推荐

  • javascript - Reading a image from url in nodejs - Stack Overflow

    I want to read a image from a url and store it in mongo db.I have basically read string values and done

    6小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信