node.js - 在mlab中上传图像

标签 node.js mongodb mongoose multer

目前我正在将 Node 休息服务器上传的图像存储在本地目录“/uploads”中。这正在不断增加我的 repo 规模。 为了避免这种情况,我想像服务一样将图像文件存储在 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;
      });
    }
})

希望这有帮助

关于node.js - 在mlab中上传图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51825874/

相关文章:

node.js - 如何在 Ubuntu 上安装最新的 Node 版本?

node.js - 用于模式定义的 Mongoose 或 MongoDB?

node.js - Mongoose 和 NodeJS 中的多个数据库使用相同的引用文件架构

node.js - 使用外部 babel 配置会破坏 Node/React 应用程序 - 内部服务器错误

javascript - 使用请求模块下载文件并将结果传递给meteor.js 中的响应

javascript - 在 JavaScript 中使用数组循环调用函数

python - 将 db.find().map 与 pymongo 一起使用

java - spring data mongodb 映射动态字段

linux - 如何在mongodb中将数据库从一台服务器复制到另一台服务器

javascript - 正确隐藏数据库凭据