2014-01-07 41 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