gpt4 book ai didi

node.js - 如何在 ExpressJS 和 multer 中将数据从一个路由器传递到另一个路由器?

转载 作者:太空宇宙 更新时间:2023-11-04 02:46:43 25 4
gpt4 key购买 nike

我有以下代码:

router.use('/', function (req, res, next) {
var token = req.headers['authorization'];
jwt.verify(token, config.secret, function (err, decoded) {
if (err) {
return res.json({
success: false,
message: 'Failed to authenticate',
error: err
});
} else {
req.decoded = decoded;
}
next();
});
})

var _storage = multer.diskStorage({
destination: function (req, file, cb) {
var dest = './express-server/uploads/users/' + req.decoded.user._id;
var stat = null;
try {
stat = fs.statSync(dest);
}
catch (err) {
fs.mkdirSync(dest);
}
if (stat && !stat.isDirectory()) {
throw new Error('Directory cannot be created because an inode of a different type exists at "' + dest + '"');
}
cb(null, dest )
},
filename: function (req, file, cb) {
crypto.pseudoRandomBytes(2, function (err, raw) {
cb(null, raw.toString('hex') + '.' + file.originalname.toLowerCase());
});
}
});

var upload = multer({storage: _storage});
imageType = upload.single('fileUpload');

router.post('/upload', imageType, function (req, res, next) {
console.log(req.file.path) // this logs out the path
res.send({success:true);
});

到目前为止一切顺利,图像从前端上传并正确存储在文件系统中。

在这条路线的正下方,我有另一条路线:

router.post('/new', function ( req, res,  next) {
var token = req.headers['authorization'];
var decoded = jwt.decode(token);
User.findById(decoded.user._id, function (err, doc) {
if (err) {
return res.status(404).json({
title: 'An error occured',
err: err
});
}

var person = new Person({
name: req.body.name,
lastName: req.body.lastName,
imageURL: **// how i can grab the uploaded file path inside this route from the upload route? Is this even possible?**,
user: doc
})

在这段代码之后,我将表单保存在 Mongodb 中,没有任何问题,我只是无法获取文件名路径。

Person.save(function (err, newPerson) {
if (err) {
return res.status(404).json({
title: 'An error occured',
err: err
});
}
doc.person.push(newPerson);
doc.save();
res.status(200).json({
message: 'Person Saved!',
obj: newPerson
});
});
});
});

有什么想法吗?

最佳答案

如果您的中间件或路由处理程序中有一个正常运行的图像保存步骤,那么最好的办法是将上传文件的公共(public) URL 添加到用户对象以便稍后保存。

我强烈建议不要将整个图像作为缓冲区存储在数据库中。虽然这是可能的,但它会给服务器带来比从磁盘发送静态文件更多的负载,并且静态文件处理有低成本选项(例如 CDN),如果存储在数据库中,则无法使用这些选项。

关于node.js - 如何在 ExpressJS 和 multer 中将数据从一个路由器传递到另一个路由器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40328082/

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