我想从 url 读取图像并将其存储在 mongo db 中。我基本上已经读取了字符串值并完成了上述过程。但是我被困在如何读取图像上。任何想法都会非常有帮助。
问问题
4218 次
1 回答
6
使用节点 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);
});
});
于 2013-02-28T09:11:15.897 回答