我想在保存之前使用sharp
处理图像,这样我就不需要保存文件两次(一次multer
保存,一次保存sharp
)。我发现的最好的方法是使用没有参数的初始化multer将文件保存在内存中:
const upload = multer()
然后在路由处理程序中将文件缓冲区提供给夏普:
await sharp(req.file.buffer)
.resize(500)
.jpeg({ quality: 50 })
.toFile(path)
);
如果有更好的方法,请告诉我。
更好的问题是: 有没有像 multer 中的钩子一样的东西在保存之前调用?所以我可以在保存之前更改文件内容。
该过程是从filefilter方法开始的,然后是multer的文件名,因此您应该开始在filefilter中调整其大小,然后将其保存到临时目录,然后在调整大小后重新调整图像,您可以使用方法。尖锐包的ToFile,它将把目的地保存在.toFile("./upload")中 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,
};
};
我的调整大小图像.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;
});
};
disk-storage.ts
const storage= diskStorage({
destination: 'upload/product',
filename: editFileName,
}),
fileFilter: imageFileFilter,
})
- 在文件中使用锐利过滤器的 multer
- 我正在使用文件映射器,因为我想为我的数据库接收新对象