我有一个:http://malsup.com/jquery/form/ ..它运行正常,但我想要一个像facebook这样的上传进度系统,当文件上传时窗口加载,上传进度显示在浏览器的左下角。是否有任何支持文件上传的jquery ajax表单提交。
答案 0 :(得分:1)
你可以用XHRListener做到这一点。 我在一段时间之前做了类似的事情,这里是我使用的代码片段:
jQuery.ajax({
url: 'url/to/upload/to',
data: formMediaData,
dataType:'json', //return type, in my case it was json
type: 'post',
xhr: function(){
// this is the important part
var xhr = new window.XMLHttpRequest();
//the event listener will call _very_ often, you might want to check
// how big the difference between the last percentage and this
//percentage is, before you do anything that needs long computing times(!)
xhr.upload.addEventListener("progress", function(evt){
//check if the browser can determine the complete size of the data.
if (evt.lengthComputable) {
var percentComplete = Math.round((evt.loaded / evt.total)*100);
//do something with the percentage...
console.log("upload " +percentComplete + "% done");
}
},false);
return xhr;
},
success: function(data){
//do some tasks after upload
console.log("upload done");
}
});
这是你添加文件的方式:
HTML:
<!-- accept="image/*" will only accept file miming to be an image, remember to check if it really is an image... -->
<input type="file" id="uploadBox" accept="image/*" onchange="handleMediaFiles(this.files)" />
JS:
var formMediaData= new FormData();
function handleMediaFiles(files){
for(var i=0;i<files.length;i++){
formMediaData.append('file_'+i,file[i]);
}
fileUpload(); // that's where the ajax is sent
}