如何使用express server调整上载图像的大小
我使用multer和multer-s3将图像上传到s3存储桶 我想保持原始图像的原样,但需要额外的缩略图。 然后将它们都上传到s3。 我发现,图像大小调整可以使用夏普,但不知道如何做这个特定的任务 有人能给我建议怎么做吗如何使用express server调整上载图像的大小,express,aws-sdk,image-resizing,multer,multer-s3,Express,Aws Sdk,Image Resizing,Multer,Multer S3,我使用multer和multer-s3将图像上传到s3存储桶 我想保持原始图像的原样,但需要额外的缩略图。 然后将它们都上传到s3。 我发现,图像大小调整可以使用夏普,但不知道如何做这个特定的任务 有人能给我建议怎么做吗 const aws = require('aws-sdk'); const multer = require('multer'); const multerS3 = require('multer-s3'); aws.config.update({ secretAcc
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);
试试这个,
使用sharpe模块
。根据需要更改路由处理程序
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();
},
保存图像后,可以调整其大小 您只需要将路径传递到图像 注意:您可以获取图像的宽度和高度,并检查图像是否需要调整大小
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。我正在将实际大小的照片保存为上传。单张(“照片”)如何将此功能放入该链中?也不确定如何获取图像的路径。在
PostController.createPost
中,您应该能够使用req.file
访问文件,尝试console.log(req.file)
您还应该看到path@Janaka在您的PostController.createPost
之前,您可以创建一个名为PostController.resizeImage
的新中间件,从中获取req.file
对象的路径,调整其大小,然后使用next()
移动到下一个中间件。我这样修改了post;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中间件之后才能访问它