如何返回上传文件的ID(在Node.js Express应用中使用multer进行上传) [英] How to return id of uploaded file (upload with multer in nodejs express app)
本文介绍了如何返回上传文件的ID(在Node.js Express应用中使用multer进行上传)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个MEAN堆栈应用程序,并尝试使用multer上传文件.上传工作正常,唯一的问题是我想返回上传文件的ID.
I have an MEAN stack app and trying to upload file with multer. Upload is working fine the only problem is I want to return uploaded file's id.
//multer settings for single upload
var upload = multer({ storage: storage }).single('file');
app.post('/upload', upload, function (req, res) {
//// ????? What to return and how?
});
我已将此帖子订阅为angular2服务. 谢谢您的帮助.
I'm subscribed to this post into angular2 service. Thank you for help.
推荐答案
var multer = require('multer');
// storage for upload file.
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './file');
},
filename: function (req, file, callback) {
callback(null, file.originalname);
}
});
var Upload = multer({
storage: storage
}).any('file');
router.post('/upload', postData);
function postData(req, res) {
Upload(req, res, function (error) {
if (error) {
res.status(400).send(error);
}
var obj = {};
obj.file = req.files.filename;
//file is getting stored into database and after it successfully stored
//into database it will return you Id
db.create(obj, function (err, data) {
if (err) {
res.send('error');
}
if (!data) {
res.send('Error');
} else {
console.log('file upload');
res.send(data._id);
}
});
});
}
要返回ID,您必须将引用存储在数据库中的某个位置,然后将ID返回给Angular2
to return Id you should have to store reference somewhere in database and after that you will return id to Angular2
这篇关于如何返回上传文件的ID(在Node.js Express应用中使用multer进行上传)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文