我在名为“uploads”的文件夹中使用Multer上传了不同类型的文件(图片,pptx,视频和docx)。
var storage = multer.diskStorage({ //multers disk storage settings
destination: function (req, file, cb) {
cb(null, './uploads/');
},
filename: function (req, file, cb) {
var datetimestamp = Date.now();
cb(null, file.originalname);
}
});
var upload = multer({ //multer settings
storage: storage
}).single('file');
/** API path that will upload the files */
app.post('/upload', function(req, res) {
upload(req,res,function(err){
if(err){
res.json({error_code:1,err_desc:err});
return;
}
res.json({error_code:0,err_desc:null});
});
});
现在上传的文件存储在'uploads'文件夹中,例如/uploads/demo.pptx
我需要获取这些并发送存储文件的文件路径或URL,并作为响应发送给客户端,以便他们可以访问观看或下载它。
答案 0 :(得分:2)
通常,当您需要做的不仅仅是为他们提供服务并上传新文件时,存储在数据库中的文件。对于此建议,您只能将文件的元数据保存到DB(例如大小,类型,路径,名称)。但是,如果由于某种原因仍需要在DB中存储文件,MongoDB会有GridFS组件并提供有关使用此组件的文档。
答案 1 :(得分:1)
你可以这样做: -
var mongojs = require('mongojs');
var db = mongojs(//credential here);
var uploaded_file=db.collection("uploaded_file");
var storage = multer.diskStorage({ //multers disk storage settings
destination: function (req, file, cb) {
cb(null, './uploads/');
},
filename: function (req, file, cb) {
var datetimestamp = Date.now();
cb(null, file.originalname);
}
});
var upload = multer({ //multer settings
storage: storage
}).single('file');
/** API path that will upload the files */
app.post('/upload', function(req, res) {
upload(req,res,function(err){
if(err){
res.json({error_code:1,err_desc:err});
return;
}else{
uploaded_file.insert(res.file,function(err, saved) {// i am asuming res.file have the information you needed to send
if(err){
console.log("Unexpected error occurred during insertion in database:"+err);
}else{
res.send({error_code:0,file_info:res.file});
res.end();
}
});
}
});
});