2014-01-07 42 views
1

客戶端代碼沒能獲得上傳到Node.js加載

$(document).ready(function(){ 
    var fileSelected; 
    console.log("Document Loaded"); 
    $('#userPhotoInput').on('change', function(e){ 
     fileSelected = e.target.files[0]; 
     console.log(fileSelected.name); 
    }); 

    $('#uploadForm').submit(function(e){ 
     e.preventDefault(); 
     console.log("Submit Clicked"); 
     $.ajax({ 
      type:'POST', 
      url :'/upload', 
      processData: false, 
      contentType: false, 
      beforeSend: function(request) { 
       request.setRequestHeader("Content-Type", fileSelected.type); 
      } 
      success : function(data){ 
       console.log(data); 
      }, 
      error : function(error){ 
       console.log(error) 
      } 
     }); 
     return false; 
    }); 
}); 

服務器端

// Global app configuration section 
app.set('views', 'cloud/views'); // Specify the folder to find templates 
app.set('view engine', 'ejs'); // Set the template engine 
app.use(express.bodyParser()); // Middleware for reading request body 
app.post('/upload',function(req,res){ 
    var response = ""; 
    for(var key in req){ 
     console.log(key); 
    response += ((!response.length) ? "" : ",") + key; 
    } 
    res.send(response.split(",")); 
}); 

我得到它在服務器上的內容長度,它是圖像好,好。但無法從請求中獲取數據。我嘗試獲取req.files,但請求中沒有像這樣的屬性。 req.body也返回一個空的對象。任何人都可以指導我嗎?

服務器日誌

Input: {"method"=>"POST", "url"=>"/upload", "headers"=>{"version"=>"HTTP/1.1", "host"=>"myhost", "user-agent"=>"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36", "content-length"=>"2348", "accept"=>"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "accept-encoding"=>"gzip,deflate,sdch", "accept-language"=>"en-US,en;q=0.8,ar;q=0.6", "cache-control"=>"max-age=0", "content-type"=>"multipart/form-data; boundary=----WebKitFormBoundaryHsBgtmA9Sojnhbpx"}} 
+0

可你也記錄頭和檢查內容類型是否正確選擇? – SridharVenkat

+0

我已在服務器代碼中追加了'app.use(express.bodyParser())''服務器日誌 – CodeDecode

+1

'。然後你可以訪問'req.files' – vinayr

回答

0

您正在使用的HTML文檔&形式無法使用......但問題是Ajax upload

通常file upload will cause a page refresh,如果你喜歡做的異步上傳你需要......

  1. 使用iframe(現在有點無聊..)。
  2. 使用可用的Jquery插件(客戶端插件)。

上計算器的答案 - upload file with a form via ajax nodejs express

此鏈接演示如何使用插件trickery AJAX文件上傳 - http://markdawson.tumblr.com/post/18359176420/asynchronous-file-uploading-using-express-and-node-js

+0

不幸的是,我使用Parse.com作爲後端,並且此解決方案沒有出現。相反,我已經創建了該文件的base64字符串並上傳了它,它確實有效。 – CodeDecode