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}",
謝謝 - 但我迄今爲止所傳遞的所有字符串都不要求我使用FormData,但文件確實需要這樣嗎? – orepor
@orepor,對於延遲抱歉,FormData對象是通過AJAX POST文件的唯一方式。否則,您會使用舊方法(隱藏框架)或使用基於Flash的文件上傳控件(比如您可以使用Apache Flex構建)進行阻止。 –