file标签改变事件 $(':file').change(function(){ var file = this.files[0]; var name = file.name; var size = file.size; var type = file.type; //Your validation });
ajax上传
$(':button').click(function(){ var formData = new FormData($('form')[0]); $.ajax({ url: 'upload.php', //Server script to process data type: 'POST', xhr: function() { // Custom XMLHttpRequest var myXhr = $.ajaxSettings.xhr(); if(myXhr.upload){ // Check if upload property exists myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload } return myXhr; }, //Ajax events beforeSend: beforeSendHandler, success: completeHandler, error: errorHandler, // Form data data: formData, //Options to tell jQuery not to process data or worry about content-type. cache: false, contentType: false, processData: false }); }); Now if you want to handle the progress.
function progressHandlingFunction(e){ if(e.lengthComputable){ $('progress').attr({value:e.loaded,max:e.total}); } }
发布评论
评论(1)
HTML页面:
<form enctype="multipart/form-data">
<input name="file" type="file" />
<input type="button" value="Upload" />
</form>
<progress></progress>
file标签改变事件
$(':file').change(function(){
var file = this.files[0];
var name = file.name;
var size = file.size;
var type = file.type;
//Your validation
});
ajax上传
$(':button').click(function(){
var formData = new FormData($('form')[0]);
$.ajax({
url: 'upload.php', //Server script to process data
type: 'POST',
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // Check if upload property exists
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
//Ajax events
beforeSend: beforeSendHandler,
success: completeHandler,
error: errorHandler,
// Form data
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});
});
Now if you want to handle the progress.
function progressHandlingFunction(e){
if(e.lengthComputable){
$('progress').attr({value:e.loaded,max:e.total});
}
}
以上用到了Html5的特性