[英]Get Picture from Client - save on MongoDB, expressJS, nodeJS
我正在嘗試實現從客戶端到mongoDB的簡單圖片上傳。 我已經閱讀了許多說明,但是從頭到尾都找不到方法。
我的客戶-
function profilePic(input) {
if (input.files && input.files[0]) {
var file = input.files[0];
localStorage.setItem('picture', JSON.stringify(file));
}
}
稍后,我從LocalStorage獲取此JSON並將其發送到我的服務器端,如下所示:
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}",
如果要通過XMLHTTPRequest()上傳Blob,則需要使用HTML 5 FormData對象:
https://developer.mozilla.org/zh-CN/docs/Web/API/FormData
它允許您指定要推送的文件名,然后像處理mime表單那樣處理傳入的文件。 請注意使用FormData對象時對瀏覽器支持的限制。 您的替代方法是將表單POST到隱藏框架,該方法可以正常工作,但在代碼中看起來不像FormData那樣干凈。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.