import multer, { FileFilterCallback } from "multer";
import sharp from "sharp";
import { NextFunction, Request, Response } from "express";
const multerStorage = multer.memoryStorage();
const multerFilter = (
req: Request,
file: Express.Multer.File,
cb: FileFilterCallback
) => {
if (file.mimetype.startsWith("image")) {
cb(null, true);
} else {
cb(new Error("Not an image! Please upload only images."), false);
}
};
const upload = multer({ storage: multerStorage, fileFilter: multerFilter });
export const uploadRecipeImages = upload.array("images", 6);
export const resizeRecipeImages = async (
req: Request,
res: Response,
next: NextFunction
) => {
if (!req.files?.images) return next();
req.body.images = [];
await Promise.all(
req.files.images.map(async (file, index) => {
const filename = `recipe-${req.params.id}-${Date.now()}-${
index + 1
}.jpeg`;
await sharp(file.buffer)
.resize(1024, 1024)
.toFormat("jpeg")
.jpeg({ quality: 90 })
.toFile(`public/img/recipes/${filename}`);
req.body.images.push(filename);
})
);
next();
};
我在 Express 应用程序中使用 multer 包。我收到两个 TypeScript 错误:
cb(new Error("Not an image! Please upload only images."), false);
if (!req.files?.images) return next();
从filefilter文档来看,
cb
只能用于以下方式:
function fileFilter (req, file, cb) {
// The function should call `cb` with a boolean
// to indicate if the file should be accepted
// To reject this file pass `false`, like so:
cb(null, false)
// To accept the file pass `true`, like so:
cb(null, true)
// You can always pass an error if something goes wrong:
cb(new Error('I don\'t have a clue!'))
}
然后,我们可以找到
FileFilterCallback
界面:
/**
* a function to control which files should be uploaded and which should be skipped
* pass a boolean to indicate if the file should be accepted
* pass an error if something goes wrong
*/
interface FileFilterCallback {
(error: Error): void;
(error: null, acceptFile: boolean): void;
}
您的代码
cb(new Error("Not an image! Please upload only images."), false);
与任何接口都不匹配。这就是您收到错误的原因。
所以你可以像
cb
一样调用cb(new Error("Not an image! Please upload only images."));
函数来匹配(error: Error): void;
接口。
.array(fieldname[, maxCount])
接受文件数组,所有文件的名称均为 fieldname。如果上传的文件超过 maxCount,则可能会出错。文件数组将存储在
.req.files
所以应该是:
if (!req.files) return next();