【问题标题】:How to resize upload images with express server如何使用快递服务器调整上传图片的大小
【发布时间】:2020-09-04 14:29:04
【问题描述】:

我正在使用 multer 和 multer-s3 将图像上传到 s3 存储桶。

我想保持原图不变,但需要额外的缩略图。 然后将它们都上传到s3。 我发现可以使用Sharp来调整图像大小,但不确定如何执行此特定任务。

任何人都可以建议如何做到这一点?

const aws = require('aws-sdk');
const multer = require('multer');
const multerS3 = require('multer-s3');

aws.config.update({
    secretAccessKey: process.env.AWSSecretKey,
    accessKeyId: process.env.AWSAccessKeyId,
});

const s3 = new aws.S3();

const fileFilter = (req, file, cb) => {
    if (file.mimetype === "image/jpeg" || file.mimetype === "image/png") {
        cb(null, true);
    } else {
        cb(new Error("Invalid file type, only JPEG and PNG is allowed!"), false);
    }
};

const storage = multerS3({
    s3: s3,
    bucket: process.env.S3_Bucket_Name,
    acl: 'public-read',
    metadata: (req, file, cb) => {
        cb(null, {
            fieldName: file.fieldname
        });
    },
    key: (req, file, cb) => {
        cb(null, Date.now().toString())
    }

});

const upload = multer({
    fileFilter: fileFilter,
    storage: storage,
});

module.exports = upload;

路由按以下方式完成

router.post('/post/add', checkAuth, upload.single("photo"), PostController.createPost);

【问题讨论】:

    标签: express aws-sdk image-resizing multer multer-s3


    【解决方案1】:

    保存图片后,您可以轻松调整其大小。

    您只需要传递图像的路径即可。

    这里注意:你可以获取图片的宽度和高度,并检查图片是否需要调整大小。

    const sharp = require("sharp");
    
    async function resizeImage(req, res) {
       let { width, height } = await sharp("path/to/image").metadata();
       let resizedImage;
       // you can check here if the image is too big. I will resize it to an width of 400
       if(width > 400) {
          await sharp("path/to/image")
              .resize({ fit: sharp.fit.contain, width: 400 })
              .jpeg({ quality: 90 })
              .toFile("path/to/thumbnail/directory);
       }
    }
    

    【讨论】:

    • 我不清楚如何将此功能连接到我的 router.post。我将实际尺寸的照片保存为 upload.single("photo") 我如何将此功能放入该链中?也不知道如何获取图像的路径。
    • 在您的PostController.createPost 中,您应该能够使用req.file 访问您的文件尝试console.log(req.file),您应该还可以看到路径
    • @Janaka 在您的PostController.createPost 之前,您可以创建一个名为PostController.resizeImage 的新中间件,您可以在其中从req.file 对象中获取路径,调整其大小,然后使用@987654328 移动到下一个中​​间件@
    • 我这样修改了帖子; router.post('/post/add', checkAuth, resizePhoto, upload.single("photo"), PostController.createPost);但是里面 resizePhoto req.file 是未定义的
    • router.post('/post/add', checkAuth, upload.single("photo"),resizeImage, PostController.createPost); 将是正确的方法。您只能在 multer 中间件之后访问它
    【解决方案2】:

    试试这个,usage of sharpe module。根据您的需要更改路由处理程序

    router.post(
      "/users/me/avatar",
      authMiddleware,
      upload.single("avatar"),
      async (req, res) => {
          const buffer = await sharpe(req.file.buffer)
            .png()
            .resize({
              width: 300,
              height: 300
            })
            .toBuffer();
          req.user.avatar = buffer;
          await req.user.save();
          res.send();
        },
    

    【讨论】:

      猜你喜欢
      • 2011-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-09
      • 2011-08-25
      • 2014-08-26
      相关资源
      最近更新 更多