Nodejs - 将图像上传到mongo文档,然后检索它

时间:2015-08-14 20:23:43

标签: node.js mongodb file-upload loopbackjs

我现在一直在苦苦挣扎。我想将图像上传到mongo,而不是GridFS,我想将图像保存在文档中。

这是我到目前为止所做的:

上传图片:

News.image = function (id, req, res, cb) {

    News.findById(id).then(function (news) {
      if (!news) return cb({name: 'Not Found', status: '404', message: 'No news was found with given Id'});
      if (!req.file) return cb({name: 'Bad Request', status: '400', message: 'No file was sent'});

      var data = req.file.toString('base64');
      app.models.Image.create({content: data, mimetype: req.file.mimetype}).then(function (img) {
        cb(null, news);
      }).catch(function (err) {
        console.log(err);
        cb(err);
      });

    });
  };

然后我在数据库中得到这个:

{ "_id" : ObjectId("55ce4ae12f409cb685283a9f"), "mimetype" : "image/png", "content" : BinData(0,"W29iamVjdCBPYmplY3Rd") }

这是我用来检索图像的代码:

Image.data = function (id, res, cb) {
    Image.findById(id).then(function (img) {
      if (!img) {
        var err = new Error("Image not found");
        err.statusCode =  404;
        throw err;
      }

      var image = new Buffer(img.content, 'base64');
      res.writeHead(200, {'Content-Type': 'image/png' });
      res.end(image, 'binary');

    }).catch(function (err) {
      console.log(err.message);
      cb(err);
    });
  };

这就是我在浏览器中收到的内容: enter image description here

我只是不知道我是否按照我需要的方式存储文件,或者我没有以正确的方式从数据库中获取文件。我怎样才能做到这一点?

0 个答案:

没有答案