【问题标题】:How can I compress an image before storing it in MongoDB using GridFS and NodeJS?如何在使用 GridFS 和 NodeJS 将图像存储到 MongoDB 之前对其进行压缩?
【发布时间】:2021-04-11 08:12:32
【问题描述】:

我正在尝试使用 GridFS 和 MongoDB 在我的 NodeJS 应用程序中上传图像。 我想在将图像上传到 MongoDB 之前对其进行压缩,并且我已经共享了 GridFS 中间件。

我想知道我应该把压缩代码放在哪里,或者是否有更好的方法来压缩图像?

require('dotenv').config();
const multer = require('multer');
const GridFsStorage = require('multer-gridfs-storage');
const Grid = require('gridfs-stream');
const Mongoose = require('mongoose');
const Mongouri = process.env.MONGO_URL;
let conn = Mongoose.connection;
let gfs;
conn.once('open',()=>{
    gfs = Grid(conn.db,Mongoose.mongo);
    gfs.collection('Posts');
});


//defining the middleware for multer so this will be called everytiime a new image is uploaded using multer 
let storage = new GridFsStorage({
    url:Mongouri,
    file:(req,file)=>{
        return new Promise(
            (resolve,reject)=>{
                const fileInfo = {
                    filename:Mongoose.Types.ObjectId()+file.originalname,
                    bucketName:"Posts"
                };
                resolve(fileInfo);
            }
        );
    }

});


//initialising multer with the middleware 
const upload = multer({storage});

module.exports = upload;

【问题讨论】:

  • 你知道这些图片大概有多大吗?特别是,您在这里期望的最大图像尺寸是多少?
  • @Tim Biegeleisen 1 MB 是用户可以上传的最大值,但我希望在存储时对其进行压缩

标签: node.js mongodb mongoose gridfs gridfs-stream


【解决方案1】:

Sharp 是一种更好的工具,可以在将图像保存到数据库之前对其进行压缩。来源-Sharp npm module

【讨论】:

  • 我应该在哪里包含清晰的代码,比如我应该在中间件本身还是在路由中使用它
  • 你能告诉我压缩图像并将它们存储在数据库中的最佳做法吗?
  • 嗨。这段代码将帮助您了解如何使用它。不要复制和粘贴它,因为它不会起作用。目的是展示如何使用 Multer 和 Sharp 模块将图像上传到数据库。这是代码pastebin link的链接
猜你喜欢
  • 2022-01-18
  • 2017-03-15
  • 2017-05-17
  • 2016-04-12
  • 2018-10-06
  • 1970-01-01
  • 2012-02-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多