我需要通过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操作来处理请求,这是正确方法吗?或者我只需要从后端发出请求,对于multer和sharp,我的意思是处理sveltekit,有没有其他选择
1条答案
按热度按时间gr8qqesn1#
这就是我发现的上传多个文件与svetekit它可能会帮助任何人.
+Page.server.js
+页面.苗条