使用multer将图像上传到mongoDB Atlas的策略?

时间:2020-03-02 12:45:03

标签: node.js express mongoose multer mongodb-atlas

我的目标是能够使用Multer将图像上传到mongoDB Atlas。目前,我已经使用express-generator建立了一个示例,其中包含以下相关文件:

app.js:

// ...
var app = express();

//Set up mongoose connection
var mongoose = require('mongoose');
var mongoDB = 'mongodb+srv://username:password@cluster0-wczgu.mongodb.net/test?retryWrites=true&w=majority';
mongoose.connect(mongoDB, { useNewUrlParser: true });
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
// ...

index.js:

var express = require('express');
var router = express.Router();
var multer = require("multer");
var fs = require("fs");
var upload = multer({ dest: 'uploads/' })
var Image = require('../models/image');

// GET for image form
router.get("/image/create", function(req, res, next) {
    res.render("create_image", {title: "Create Image"});
});

// Uploading image to mongoDB Atlas
router.post("/image/create", upload.single("image"), function(req, res, next) {
    var image = new Image({
        name: req.body.image_name
    });
    image.img.data = fs.readFileSync(req.file.path);
    image.img.contentType = "image/jpg";
    image.save(function(err) {
        if (err) { return next(err); }
        res.redirect("/");
    });
});

// Show some random image
router.get("/image", function(req, res, next) {
    Image.findOne({}, function(err, image) {
        if (err) { return next(err); }
        res.contentType(image.img.contentType)
        res.send(image.img.data);
    });
});

image.js(图像模式):

var mongoose = require("mongoose");

var Schema = mongoose.Schema;

var ImageSchema = new Schema(
    {
        name: {type: String, required: true, max: 100},
        img: {data: Buffer, contentType: String}
    }
);

module.exports = mongoose.model("Image", ImageSchema);

最后是用于创建图像的表单create_image.pug:

extends layout

block content
    h1= title

    form(action="" method="POST" enctype="multipart/form-data")
        label(for="image_name") Name of Image:
        input#image_name.form-control(type="text" placeholder="Name of image" name="image_name" required="true")
        input(type="file" name="image")
        button(type='submit') Submit

这样做很好,因为图像存储在MongoDB Atlas中,但它也将图像存储在本地。现在从生产的角度来看,这不是一个好主意,因为该项目会变得很大。但是我似乎无法找出正确的方法来做这件事?

有人可以告诉我正确的做法,这样我只能将图像存储在MongoDB Atlas上,而不是本地存储吗?还可能告诉我,如果我把整个事情都弄错了,应该以完全不同的方式做到这一点吗?

1 个答案:

答案 0 :(得分:2)

如果您不想在本地存储图像,请将MemoryStorage用作Multer Storage。

var storage = multer.memoryStorage()
var upload = multer({ storage: storage })

使用内存存储时,文件信息将包含一个名为buffer的字段,其中包含整个文件。因此,您不必致电fs.readFileSync。您可以使用req.file.image.buffer访问缓冲区并分配图像数据;

image.img.data = req.file.image.buffer;