2013-02-28 81 views
0

我想从url读取图像并将其存储在mongo db.I基本上已经读取了字符串值并完成了上述过程。但是我坚持如何读取图像。任何想法在那将是非常有帮助的。在nodejs中从url读取图片

+0

您需要下载镜像或存储或格式? – diolemo 2013-02-28 07:07:49

+0

只需要下载img并写入文件系统 – williamC 2013-02-28 07:11:04

+0

例如,如果我有一个url作为本地主机:1340/promotionDetails?promotion_id = PROM008765我读取使用快速模块的promotion_id作为req.id.Can我做同样的图像? – 2013-02-28 07:17:50

回答

4

测试节点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); 

    }); 

});