我在项目中使用multer.js
在用户注册时上传用户个人资料图片。
我需要存储用户图像文件并制作缩略图。制作缩略图时,我使用gm.js
。贝洛斯是我的代码。
import { Router } from 'express';
import User from '../models/user.model';
import passport from 'passport';
import gm from 'gm';
import multer from 'multer';
const router = new Router();
const upload = multer({ dest: './static/img/user/' });
const _saveThumbnail = (fileName) => {
return new Promise((resolve, reject) => {
gm(`img/user/${fileName}`).thumb(48, 48, `img/user/thumb_${fileName}`, 100, (err) => {
if (err) reject(new Error(err));
resolve();
});
});
};
router.post('/api/users', upload.single('img'), (req, res) => {
const fileName = req.file ? req.file.filename : 'default.png';
Promise.all([_getColRank(4), _getBattleRank(1000)]).then((ranks) => {
const user = new User({
email: req.body.email,
nickname: req.body.nickname,
password: req.body.password,
img: fileName,
introduce: req.body.introduce,
recommender: req.body.recommender,
colPoint: 4,
colRank: ranks[0],
battleRank: ranks[1],
});
_saveThumbnail(fileName).then(() => {
User.register(user, user.password, (err, savedUser) => {
if (err) return res.status(500).send(err);
passport.authenticate('local')(req, res, () => {
res.json({ savedUser });
});
});
});
});
});
export default router;
我认为upload.single('img')
是帖子的中间件,可以完成上传图片,因此gm
会将上传的图片制作成缩略图。但没有任何反应。 _saveThumbnail
返回resolve()
,原始图片已上传。
我真想制作缩略图。帮助我。
答案 0 :(得分:2)
我找到了答案。错误的一点是图像路径。
我改变了我的代码如下。
import { Router } from 'express';
import User from '../models/user.model';
import passport from 'passport';
import gm from 'gm';
import multer from 'multer';
const router = new Router();
const upload = multer({ dest: './static/img/user/' });
const _saveThumbnail = (imagePath) => { // edited arg
return new Promise((resolve, reject) => {
gm(imagePath).thumb(48, 48, `${imagePath}_thumb`, 100, (err) => { // edited
if (err) reject(new Error(err));
resolve();
});
});
};
router.post('/api/users', upload.single('img'), (req, res) => {
const fileName = req.file ? req.file.filename : 'default.png';
const imagePath = req.file ? req.file.path : null; // added
Promise.all([_getColRank(4), _getBattleRank(1000)]).then((ranks) => {
const user = new User({
email: req.body.email,
nickname: req.body.nickname,
password: req.body.password,
img: fileName,
introduce: req.body.introduce,
recommender: req.body.recommender,
colPoint: 4,
colRank: ranks[0],
battleRank: ranks[1],
});
_saveThumbnail(imagePath).then(() => { // edited arg
User.register(user, user.password, (err, savedUser) => {
if (err) return res.status(500).send(err);
passport.authenticate('local')(req, res, () => {
res.json({ savedUser });
});
});
});
});
});
导出默认路由器;