繁体   English   中英

无法将图像上传到Node.js

[英]Not Able To Get The Image Uploaded To 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"}}

您正在使用的html文档和表单不可用...但是问题在于Ajax upload

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

  1. 使用iframe(现在有点无聊..)。
  2. 使用可用的Jquery插件(客户端插件)。

上一个stackoverflow答案- 通过Ajax Node.js Express上传带有表单的文件

此链接演示了使用插件trickery ajax文件上传trickery : //markdawson.tumblr.com/post/18359176420/asynchronous-file-uploading-using-express-and-node-js

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM