2016-07-17 36 views
0

我想將圖像base64保存到db(mongodb),但不知道如何在node.js中獲取請求。將formdata上傳到node.js

這是我cilent端代碼

$('.imageUp').change(function(){ 

     upload(new FormData(this)) 
}) 

function upload(formData){ 
$.ajax({ 
     url: '/upload_img', 
     type: 'POST', 
     data: formData, 
     processData: false 
    }) 
} 

那我應該在節點呢?

router.post('/upload_img', function(req, res, next) { 
// what to do here? how to get the post file? I'm going to save it to mongodb 
}); 
+0

我知道它也許不是你的問題的概念,但我更喜歡在上傳文件使用的iframe 創建iframe在運行時 使用('enctype','multipart/form-data')在iframe主體中創建表單的形式 – Marwan

+1

不是解決方案FormData()的問題需要一個可選的' form'元素作爲它的參數,而不是'input'元素。你應該使用'新的FormData()'和'formData.append()'。 – JLRishe

+0

@JLRishe我不明白 –

回答

0

使用.append()在在客戶端FormData對象傳遞FormData包含用戶選擇File對象upload

$(".imageUp").change(function() { 
    var data = new FormData(); 
    // requires two parameters to be passed 
    data.append("file", this.files[0]); 
    upload(data) 
})