这个过程是从fileFilter方法开始,然后是multer的fileName,所以你应该开始在fileFilter中调整它的大小,将它保存到临时目录,然后在调整大小后重新调整图像,你可以使用sharp包的.ToFile方法,它将把目的地保存在.toFile( “./上传”)
file-mapper.ts(用于返回另一个对象)
export const fileMapper = ({ file, req }: FileMapper) => {
if (!file) {
return null!;
}
const fileName = editFilename(req.file);
const image_url = `${req.protocol}://${req.headers.host}/${req.file.destination}/${fileName}`;
resizeImage(req, fileName);
return {
filename: file.filename,
image_url,
path: file.path,
};
};
我的 resize-image.ts
import { Request } from 'express';
import path from 'path';
import sharp from 'sharp';
import fs from 'fs';
export const resizeImage = async (req: Request, fileName: string) => {
await sharp(req.file.path)
.resize({ height: 700, width: 700, position: 'center' })
.jpeg({ quality: 90, chromaSubsampling: '4:4:4' })
.toFile(path.resolve(req.file.destination, fileName))
.then((sharpOutPut) => {
if (sharpOutPut) fs.unlinkSync(req.file.path);
})
.catch((err) => {
throw err;
});
};
磁盘存储.ts
const storage= diskStorage({
destination: 'upload/product',
filename: editFileName,
}),
fileFilter: imageFileFilter,
})
- 在multer的fileFilter中使用sharp
- 我正在使用 fileMapper,因为我想为我的数据库接收新对象