客户端代码
$(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"}}发布于 2014-01-08 06:24:19
您正在使用的html文档和表单不可用.但问题在于Ajax upload。
通常是file upload will cause a page refresh,如果你想做上传异步,你需要.
先前的堆栈溢出答案- upload file with a form via ajax nodejs express
此链接演示使用插件trickery - http://markdawson.tumblr.com/post/18359176420/asynchronous-file-uploading-using-express-and-node-js上载ajax文件。
https://stackoverflow.com/questions/20974360
复制相似问题