2016-05-06 44 views
3

我正在使用Express,Node.js和Mongodb創建上傳並顯示圖像文件的網頁。在貓鼬模式下以二進制數據存儲圖像文件並以html格式顯示圖像

我使用模式在mongodb中保存了圖像的二進制文件。

這是我的index.js和db.js碼點點..

var Post = mongoose.Schema({ 
    image: {data: Buffer, contentType: String} 
}); 

var post= new Post({ }); 
post.image.data=fs.readFileSync(req.file.path); 
post.image.contentType='image/png'; 

,這裏是蒙戈外殼的一部分,我提交的圖像文件,並尋找崗位後,它的像場

"image:  {"data:BinData(0,"iVBORw0KGgoAAAANSUhEUE....(I 
just cut off the rest of the code.. cuz it was too long)   
rkJggg=="), 
"contentType" : "image/png" } 

所以它看起來像它的成功節省mogngodb圖像文件的二進制數據,

但我的問題是如何顯示的圖像在現在使用二進制數據的網頁上。如何轉換二進制緩衝區數據以創建圖像標籤?

<img src= "data:{{image.contentType}};base64,{{image.data}}"> 

我嘗試這樣做,但它給了我一個錯誤:

Failed to load resource: net::ERR_INVALID_URL 

難道你們,請讓我知道我該如何解決這個問題?我會非常感謝你的幫助:(((

回答

2

首先,你必須將緩衝區數據轉換爲base64,你可以在後臺或前端使用它無關緊要,只需使用yourBufferData.toString('base64')即可。然後,你可以使用它

然而,我會建議另一種方式來存儲圖像,而不是存儲二進制數據假設你使用nodejs你可以使用fs.writeFile方法在存儲庫中創建具有該二進制數據的圖像然後你可以存儲(db)中的圖像路徑,然後,將文件路徑放到你保存的ng-src =「文件路徑中」,下面是我使用的示例:

var path = 'upload/profiles/' +req.body.userId + '_profile.jpg'; 
     fs.writeFile(path, base64data, function(err) { 
     if (err) return next(err); 
     User.findByIdAndUpdate({ 
      _id: req.body.userId 
     }, { 
      $set: { 
      profileImg: 'upload/profiles/' +req.body.userId + '_profile.jpg' 
      } 
     }, function(err, user) { 
      if (err) return next(err); 
      return res.send(user); 
     }); 
     }); 

    <img ng-src="savedpath"> 
+0

嗨@semih你能告訴我一種方法來直接存儲我的base64圖像字符串在數據庫中,而不是文件路徑? –

+2

好主意,但是當您的Nodejs API位於負載平衡器後面時,通常不是在文件系統上存儲任何內容的好主意。 –

相關問題