gpt4 book ai didi

node.js - 使用 multer 何时完成图像上传?

转载 作者:太空宇宙 更新时间:2023-11-03 23:31:19 27 4
gpt4 key购买 nike

我在我的项目中使用 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;

我假设post的中间件upload.single('img')完成了图片的上传,所以gm将上传的图片带到制作它的缩略图。但什么也没发生。 _saveThumbnail 返回 resolve() 并且原始图像已上传。

我真的很想制作缩略图。帮助我。

最佳答案

我找到了答案。错误点是图像路径。

我更改了代码,如下所示。

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 });
});
});
});
});
});

导出默认路由器;

关于node.js - 使用 multer 何时完成图像上传?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37949393/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com