[英]How to get the path to a file outside the root folder in React application
[英]How to get the filename and file path of files already stored in a folder?
我在名為“ 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/demo.pptx等“上傳”文件夾中
我需要獲取這些文件並發送存儲文件的文件路徑或url,並將其作為響應發送給客戶端,以便他們可以訪問以觀看或下載它。
通常,存儲在數據庫中的文件不僅需要服務並上傳新文件,還需要做更多的事情。 為此,您只能將文件的元數據(例如大小,類型,路徑,名稱)保存到DB。 但是,如果由於某種原因您仍然需要在DB中存儲文件,則MongoDB具有GridFS組件,並提供了有關使用此組件的文檔。
你可以做這樣的事情:
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();
}
});
}
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.