我需要通过 sveltekit 操作上传图像,我在后端 node.js 和代码中使用了三个函数来实现。
import multer from 'multer';
import sharp from 'sharp';
const multerStorage = multer.memoryStorage();
const multerFilter = (req, file, cb) => {
if (file.mimetype.startsWith('image')) {
cb(null, true);
}
else {
cb('Please upload only images !', false);
}
};
const upload = multer({
storage: multerStorage,
fileFilter: multerFilter,
});
const uploadFiles = upload.array('images', 10);
exports.uploadImages = (req, res, next) => {
uploadFiles(req, res, (err) => {
if (err instanceof multer.MulterError) {
if (err.code === 'LIMIT_UNEXPECTED_FILE') {
return res.send('Too many files to upload !');
}
} else if (err) {
return res.send(err);
}
next();
});
};
exports.resizeImages = async (req, res, next) => {
if (!req.files) return next();
req.body.images = [];
await Promise.all(
req.files.map(async (files,i) => {
const newFilename = `tour-${files.originalname}-${Date.now()}-${i + 1}.jpeg`;
await sharp(files.buffer)
.resize(640, 320)
.toFormat('jpeg')
.jpeg({ quality: 90 })
.toFile(`upload/${newFilename}`);
req.body.images.push(newFilename);
// console.log(req.body.images);
})
);
next();
};
exports.getResultImages = async (req, res,next) => {
if (req.body.images.length <= 0) {
return res.send(`You must select at least 1 image !`);
}
const images = req.body.images.map((image) => '' + image + '');
// res.status(200).json(req.body.images)
req.body.images = images;
res.locals.images = images;
console.log();
next();
};
所以,我怎么能用 sveltekit 操作来处理 req 超过 req,这是正确的方法还是我只需要从后端制作 req,还有 multer 和 sharp 的替代方案我的意思是处理 sveltekit