我已经为此工作了几个小时,但仍然无法提出解决方案!我的原始代码是检查使用multer上传的单个图像的模仿类型,并且效果很好,但是我很难将此代码应用于多个图像。我不确定我是否正在采用正确的方法,并且可能需要提出一种新方法。请参见下面的代码:
多重中间件
const multerOptions = {
storage: multer.memoryStorage(),
fileFilter(req, file, next) {
const isPhoto = file.mimetype.startsWith('image/');
if(isPhoto) {
next(null, true);
} else {
next({ message: 'That filetype isn\'t allowed!'}, false);
}
}
};
单个图像的原始杂波功能
exports.upload = multer(multerOptions).single('photo');
exports.resize = async (req, res, next) => {
// check if there is no new file to resize
if (!req.file) {
next(); // skip to the next middleware
return;
}
const extension = req.file.mimetype.split('/')[1];
req.body.photo = `${uuid.v4()}.${extension}`;
// resize the image
const photo = await jimp.read(req.file.buffer);
await photo.resize(800, jimp.AUTO);
await photo.write(`./public/uploads/${req.body.photo}`);
next();
};
用于多张图像的新Multer功能
exports.upload = multer(multerOptions).array('photo',[5]);
exports.resize = async (req, res, next) => {
// check if there is no new file to resize
if (!req.files) {
next(); // skip to the next middleware
return;
}
imageArray = req.files;
const extensions = [];
for (var i = 0; i < imageArray.length; i++) {
imageArray[i].mimetype.split('/')[1].push(extensions);
}
// I HAVEN'T MADE IT PAST THIS LINE YET AND AM STILL STUCK ABOVE
req.body.photo = `${uuid.v4()}.${extension}`;
// resize the image
const photo = await jimp.read(req.files.buffer);
await photo.resize(800, jimp.AUTO);
await photo.write(`./public/uploads/${req.body.photo}`);
next();
};
答案 0 :(得分:0)
很难确切地知道出了什么问题,但是通过使用async await,您不能简单地将单个工作示例包装在for循环中吗?例如:
imageArray = req.files;
for (var i = 0; i < imageArray.length; i++) {
const file = imageArray[i]
const extension = file.mimetype.split('/')[1]
const name = `${uuid.v4()}.${extension}`
// resize the image
const photo = await jimp.read(file.buffer)
await photo.resize(800, jimp.AUTO)
await photo.write(`./public/uploads/${name}`)
}
next()
从字面上看,这确实是您在单个示例中所拥有的,但是包裹在一个循环中。