2014-03-26 19 views
0

我試圖從客戶端實現一個簡單的圖片上傳到我的mongoDB。 我讀過很多解釋,但我從頭到尾找不到方法。從客戶端獲取圖片 - 保存在MongoDB,expressJS,nodeJS

我的客戶方 -

function profilePic(input) { 
    if (input.files && input.files[0]) { 
     var file = input.files[0]; 
     localStorage.setItem('picture', JSON.stringify(file)); 
    } 

} 

後來我把這個JSON從localStorage的,並將其發送到我的服務器端是這樣的:

var request = false; 
    var result = null; 
    request = new XMLHttpRequest(); 
    if (request) { 
     request.open("POST", "usersEditProf/"); 
     request.onreadystatechange = function() { 
      if (request.readyState == 4 && request.status == 200) { 
       .....//More code to send to Server 
     request.setRequestHeader('content-type', 'application/json'); 
     request.send(JSON.stringify(localStorage.getItem('picture))); 
    } 
} 

在我的服務器端:

 app.post('/usersEditProf/',users.editProfile); 
    /** Edits the Profile - sends the new one **/ 
    exports.editProfile = function(req, res) { 
    var toEdit = req.body; 
    var newPic = toEdit.picture; 

那就是我迷路的地方。是newPic居然拿着照片?我懷疑它... 我是否需要改變路徑?什麼是我需要給圖片的新途徑? 如何將它放入我的數據庫?我需要GridFS嗎?

當試圖簡單地說,我的收藏,它看起來像這樣(例如,用圖像稱爲bar.jpg:

picture: "{\"webkitRelativePath\":\"\",\"lastModifiedDate\":\"2012-10-08T23:34:50.000Z\",\"name\":\"bar.jpg\",\"type\":\"image/jpeg\",\"size\":88929}", 

回答

0

如果你想通過XMLHTTPRequest的()上傳一個blob,您需要使用HTML 5 FORMDATA對象:

https://developer.mozilla.org/en-US/docs/Web/API/FormData

它alows您指定的文件名來推動,那麼你處理傳入的文件,你會用啞劇的形式後的注意事項,當你使用瀏覽器支持的限制。 FormData對象克拉。你的替代方案是一個隱式框架的POST表單,它工作正常,但不像FormData那樣清晰。

+0

謝謝 - 但我迄今爲止所傳遞的所有字符串都不要求我使用FormData,但文件確實需要這樣嗎? – orepor

+0

@orepor,對於延遲抱歉,FormData對象是通過AJAX POST文件的唯一方式。否則,您會使用舊方法(隱藏框架)或使用基於Flash的文件上傳控件(比如您可以使用Apache Flex構建)進行阻止。 –