在 mlab 中上传图片

uploading images in mlab

目前我正在将节点休息服务器上传的图像存储在本地目录“/uploads”中。这不断增加我的回购规模。 为了避免这种情况,我想像服务一样将图像文件存储在 mongoDB atlas 或 mlab 中。

    const express = require("express");
    const router = express.Router();
    const mongoose = require("mongoose");
    const multer = require('multer');

    const storage = multer.diskStorage({
      destination: function(req, file, cb) {
        cb(null, './uploads/');
      },
       filename: function(req, file, cb) {
        cb(null, new Date().toISOString() + file.originalname);
      }
    });

    const fileFilter = (req, file, cb) => {
     // reject a file
     if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png')           
     {
      cb(null, true);
      } else {
        cb(null, false);
     }
    };

    const upload = multer({
      storage: storage,
      limits: {
        fileSize: 1024 * 1024 * 5
      },
      fileFilter: fileFilter
    });

请帮帮我。提前致谢。

您可以通过使用 mongoose Schema 和 fs 核心模块对图像进行编码并取消文件与 /uploads 的链接来实现此目的。

我将从创建一个 Mongoose 模式开始,以设置您要存储的与上传文件相关的所有信息的模型。

我将在此示例中使用 base64 编码。

uploadModel.js

const mongoose = require('mongoose');
const fs = require('fs');
const Schema = mongoose.Schema;

mongoose.set('useCreateIndex', true);

let uploadSchema = new Schema({
    name: {
      type: String,
    },
    mimetype: {
      type: String,
    },
    size: {
      type: Number,
    },
    base64: {
      type: String,
    }
})

module.exports = mongoose.model('upload',uploadSchema);

建立模型后,创建一个 base64 编码函数,module.exports 也如此。

要对您的文件进行编码,请使用 fs.readFileSync(path_to_file, encode_type)。在文件被编码并保存在变量中后,您可以使用 fs.unlink(path_to_file) 将文件从 /uploads 文件夹中删除。

uploadModel.js

module.exports.base64_encode = function(file) {
  return new Promise((resolve, reject) => {
    if(file == undefined){
      reject('no file found');
    } else {
      let encodedData = fs.readFileSync(file, 'base64');
      fs.unlink(file);
      resolve(encodedData.toString('base64'));
    }
  })
} 

现在在你的路由文件中需要你的模型。

route.js

const Upload = require('path_to_uploadModel');

router.post('/path_to_upload', upload.single('form_name_of_file'), (req, res) => {
  let img = req.file;

  let model = new Upload({
    name: img.originalname,
    size: img.size,
    mimetype: img.mimetype,
  })


  Upload.base64_encode(img.path)
    .then((base64) => {
      model['base64'] = base64;
      model.save((err)=> {
        if(err) throw err;
      });
    }
})

希望对您有所帮助