2015-06-21 75 views
0

我在基於nodejs的應用程序中使用了mongoskin。我已經使用GridFS上傳文件。我可以使用「文件名」上傳和讀取它,但是我想使用_id讀回它。我能怎麼做?以下是代碼細節。使用mongoskin&nodejs基於_ID從GridFS讀取文件

工作代碼改爲基於文件名的文件:

exports.previewFile = function (req, res) { 
    var contentId = req.params.contentid; 
    var gs = DBModule.db.gridStore('69316_103528209714703_155822_n.jpg', 'r'); 
    gs.read(function (err, data) { 
     if (!err) { 
      res.setHeader('Content-Type', gs.contentType); 
      res.end(data); 
     } else { 
      log.error({err: err}, 'Failed to read the content for id '+contentId); 
      res.status(constants.HTTP_CODE_INTERNAL_SERVER_ERROR); 
      res.json({error: err}); 
     } 
    }); 
}; 

這怎麼可以修改代碼,使其基於ID的工作原理?

回答

0

幾經打擊&試用下面的代碼工程。這是令人驚訝的bcz輸入參數似乎搜索所有的領域。

//view file from database 
exports.previewContent = function (req, res) { 
    var contentId = new DBModule.BSON.ObjectID(req.params.contentid); 
    console.log('Calling previewFile inside FileUploadService for content id ' + contentId); 

    var gs = DBModule.db.gridStore(contentId, 'r'); 
    gs.read(function (err, data) { 
     if (!err) { 
      //res.setHeader('Content-Type', metadata.contentType); 
      res.end(data); 
     } else { 
      log.error({err: err}, 'Failed to read the content for id ' + contentId); 
      res.status(constants.HTTP_CODE_INTERNAL_SERVER_ERROR); 
      res.json({error: err}); 
     } 
    }); 
};