无法将图像上传到Node.js

时间:2014-01-07 14:36:52

标签: javascript jquery ajax 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也返回一个空Object。任何人都能指导我吗?

服务器日志

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"}}

1 个答案:

答案 0 :(得分:0)

html doc&您正在使用的表单不​​可用...但问题出在Ajax upload

通常file upload will cause a page refresh,如果您想要上传异步,则需要...

  1. 使用iframe(现在有点无聊......)。
  2. 使用可用的Jquery插件(客户端插件)。
  3. 上一次stackoverflow回答 - 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