使用 Node.js/Express 和 Mongoose 在 MongoDB 中存储图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29780733/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:39:38  来源:igfitidea点击:

Store an image in MongoDB using Node.js/Express and Mongoose

node.jsmongodbmongoose

提问by Bryan Cho

Currently I handle image uploads using angular-file-upload and I simply save the image to the server's file system and reference it in the HTML. However, I want to try and store the image directly in the database within the Schema I defined for my blog posts.

目前我使用 angular-file-upload 处理图像上传,我只是将图像保存到服务器的文件系统并在 HTML 中引用它。但是,我想尝试将图像直接存储在我为博客文章定义的架构内的数据库中。

var blogSchema = new Schema({
    title: String,
    author: String,
    body: String,
    likes: { type: Number, default: 0 },
    comments: [{ type: Schema.Types.ObjectId, ref: 'Comment' }],
    date: { type: Date, default: Date.now },
    imageURL: String   // instead of this

    image: // store it directly
});

"imageURL: String" stores the path to the image.

I want to make it so that I can just have a field that stores the image itself. I was thinking that I could perhaps just upload the image like I already do, but instead convert the image after it has been uploaded and store it in binary (or some other form) in Mongo. Is this possible?

我想这样做,以便我可以拥有一个存储图像本身的字段。我在想我也许可以像我已经做的那样上传图像,而是在上传后转换图像并将其以二进制(或其他形式)存储在 Mongo 中。这可能吗?

Thanks!

谢谢!

回答by Alex

This example below shows how to upload an image to MongoDB using mongoose. Click this link for the original source

下面的这个例子展示了如何使用 mongoose 将图像上传到 MongoDB。单击此链接以获取原始来源

var express = require('express');
var fs = require('fs');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var imgPath = '/path/yourimage.png';

mongoose.connect('localhost', 'testing_storeImg');

var schema = new Schema({
    img: { data: Buffer, contentType: String }
});

var A = mongoose.model('A', schema);

mongoose.connection.on('open', function () {
  console.error('mongo is open');

  A.remove(function (err) {
    if (err) throw err;

    console.error('removed old docs');

    // store an img in binary in mongo
    var a = new A;
    a.img.data = fs.readFileSync(imgPath);
    a.img.contentType = 'image/png';
    a.save(function (err, a) {
      if (err) throw err;

      console.error('saved img to mongo');

      // start a demo server
      var server = express.createServer();
      server.get('/', function (req, res, next) {
        A.findById(a, function (err, doc) {
          if (err) return next(err);
          res.contentType(doc.img.contentType);
          res.send(doc.img.data);
        });
      });

      server.on('close', function () {
        console.error('dropping db');
        mongoose.connection.db.dropDatabase(function () {
          console.error('closing db connection');
          mongoose.connection.close();
        });
      });

      server.listen(3333, function (err) {
        var address = server.address();
        console.error('server listening on http://%s:%d', address.address, address.port);
        console.error('press CTRL+C to exit');
      });

      process.on('SIGINT', function () {
        server.close();
      });
    });
  });

});

回答by Krzysztof Sikora

router.get("/show/:i", function (req, res) {

    var dataGet = {_id: req.params.i}

    fileModel.findOne(dataGet).exec(function (err, doc) {
        if (err) {
            return next(err)
        }

        var base64dataa = new Buffer(doc.fileData, 'binary').toString('base64');


        var ress = {
            fileData: base64dataa,
            mime: doc.mimeType,
            name: doc.fileName
        }

        // res.json(ress)
        res.contentType('image/jpeg')
        res.send(doc.fileData)
    })
});


router.post('/display/', function (req, res) {
    var data = {
        file: req.body.fileData,
        mime: req.body.mime,
        name: req.body.name
    }

    res.json(data)
})

回答by Krzysztof Sikora

This is code which save data into mongodb. datais binary. I can display this 'image/jpg,base64,{{data}}' but I don't understand how can I display base64data.

这是将数据保存到 mongodb 的代码。 data是二进制的。我可以显示这个 'image/jpg,base64,{{data}}' 但我不明白如何显示base64data.

file.on('data', function (data) {
            buffer += data;

            var file = new fileModel({
                fileData: data
            })

var Busboy = require('busboy');

router.post('/upload', function (req, res) {

    var busboy = new Busboy({headers: req.headers});
    var base64data = "";
    var filetype = "";
    var name = "";
    var argum = [];
    var data2

    busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {

        var buffer = "";
        filetype = mimetype;
        name = filename;


        // file.setEncoding('base64');


        file.on('data', function (data) {
            buffer += data;

            var file = new fileModel({
                fileData: data
            })
            //
            file.save(function (err, file) {
                if (err) {
                    return next(err)
                }
                // res.json(201, newData)
                // console.log("Save in database" + file.desc)
            })
        });
        file.on('end', function () {
            base64data = buffer;
        });
    });


    busboy.on('field', function (fieldname, val, fieldnameTruncated, valTruncated) {

        argum.push(val);
    });
    busboy.on('finish', function () {
        var base64dataa = new Buffer(base64data, 'binary').toString('base64');
        res.json(base64dataa)
        var jsonBin = {
            base64data_: base64data, mime_: filetype, name_: name,
            owner_: argum[0], description_: argum[1]
        }

        // res.json(jsonBin)

        var file = new fileModel({
            fileData: jsonBin.base64data,
            mimeType: jsonBin.mime_,
            fileName: jsonBin.name_,
            fileOwner: jsonBin.owner_,
            desc: jsonBin.description_
        })
        //
        file.save(function (err, file) {
            if (err) {
                return next(err)
            }
            // res.json(201, newData)
            console.log("Save in database" + file.desc)
        })
    });

    req.pipe(busboy);
});