如何在使用 multer 上传到 S3 之前调整图像大小

时间:2021-05-21 15:57:27

标签: node.js amazon-s3 multer

这是我的代码,它工作正常,我只是希望在高达 s3 亚马逊云之前调整图像大小。

import multer from 'multer';
import path from 'path';
import multerS3 from 'multer-s3';
import aws from 'aws-sdk';

const storageType = {
    s3: multerS3({
        s3: new aws.S3(),
        bucket: 'restsystemplatesimage',
        contentType: multerS3.AUTO_CONTENT_TYPE,
        acl: 'public-read',
        key: (req, file, cb) => {
            console.log(file);
            //const restCod = req.params.data.split('|')
            cb(null, file.originalname);
        }
    })
}

export default {
    storage: storageType['s3'],
    limits: {
        filesize: 1 * 1024 * 1024
    },
    fileFilter: (req, file, cb) => {
        const allowedMimes = [
            "image/jpeg",
            "image/jpg",
            "image/png"
        ];
        if (allowedMimes.includes(file.mimetype)) {
            cb(null, true);
        }else {
            cb( new Error("Invalid file type"));
        }
    }
};

当我在控制台上打印文件时,它显示...

{
  fieldname: 'image',
  originalname: 'espetinho-de-carne.jpg',
  encoding: '7bit',
  mimetype: 'image/jpeg'
}

缓冲区对象不应该出现吗?如果我不知道它在哪里,我无法修改图像

请人帮忙

1 个答案:

答案 0 :(得分:0)

我找到了解决方案,我没有使用包multer-s3,而是使用包multer-sharp-s3,并对我的代码进行了这些更改

import multer from 'multer';
import path from 'path';
import multerS3 from 'multer-sharp-s3';
import aws from 'aws-sdk';

const storageType = {
    s3: multerS3({
        s3: new aws.S3(),
        Bucket: 'restsystemplatesimage',
        resize: {
            width: 320,
            height: 192
          },
        ACL: 'public-read',
        key: (req, file, cb) => {
            console.log(file);
            //const restCod = req.params.data.split('|')
            cb(null, file.originalname);
        }
    })
}

export default {
    storage: storageType['s3'],
    limits: {
        filesize: 1 * 1024 * 1024
    },
    fileFilter: (req, file, cb) => {
        const allowedMimes = [
            "image/jpeg",
            "image/jpg",
            "image/png"
        ];
        if (allowedMimes.includes(file.mimetype)) {
            cb(null, true);
        }else {
            cb( new Error("Invalid file type"));
        }
    }
};
´´´
相关问题