js獲取文件上傳進度: js監聽: ajax文件上傳函數: 完整代碼: ...
js獲取文件上傳進度:
<input name="file" id="FileUpload" type="file" /> <input type="button" onclick="Submit()" value="提交" />
js監聽:
var xhrOnProgress=function(fun) { xhrOnProgress.onprogress = fun; //綁定監聽 //使用閉包實現監聽綁 return function() { //通過$.ajaxSettings.xhr();獲得XMLHttpRequest對象 var xhr = $.ajaxSettings.xhr(); //判斷監聽函數是否為函數 if (typeof xhrOnProgress.onprogress !== 'function') return xhr; //如果有監聽函數並且xhr對象支持綁定時就把監聽函數綁定上去 if (xhrOnProgress.onprogress && xhr.upload) { xhr.upload.onprogress = xhrOnProgress.onprogress; } return xhr; } }
ajax文件上傳函數:
function Submit(){ var fileObj = document.getElementById("FileUpload").files[0]; // js 獲取文件對象 var formFile = new FormData(); formFile.append("file", fileObj); //加入文件對象 var data = formFile; $.ajax({ url: url, data: data, type: "Post", dataType: "json", cache: false,//上傳文件無需緩存 processData: false,//用於對data參數進行序列化處理 這裡必須false contentType: false, //必須 xhr:xhrOnProgress(function(e){ var percent=e.loaded/e.total;//文件上傳百分比 console.log(percent); }), success: function (result) { console.log(result); }, }) }
完整代碼:
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Document</title> </head> <body> <input name="file" id="FileUpload" type="file" /> <input type="button" onclick="Submit()" value="提交" /> </body> <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> <script type="text/javascript"> var xhrOnProgress=function(fun) { xhrOnProgress.onprogress = fun; //綁定監聽 //使用閉包實現監聽綁 return function() { //通過$.ajaxSettings.xhr();獲得XMLHttpRequest對象 var xhr = $.ajaxSettings.xhr(); //判斷監聽函數是否為函數 if (typeof xhrOnProgress.onprogress !== 'function') return xhr; //如果有監聽函數並且xhr對象支持綁定時就把監聽函數綁定上去 if (xhrOnProgress.onprogress && xhr.upload) { xhr.upload.onprogress = xhrOnProgress.onprogress; } return xhr; } } function Submit(){ var fileObj = document.getElementById("FileUpload").files[0]; // js 獲取文件對象 var formFile = new FormData(); formFile.append("file", fileObj); //加入文件對象 var data = formFile; $.ajax({ url: "http://up.qiniu.com/", data: data, type: "Post", dataType: "json", cache: false,//上傳文件無需緩存 processData: false,//用於對data參數進行序列化處理 這裡必須false contentType: false, //必須 xhr:xhrOnProgress(function(e){ var percent=e.loaded/e.total; console.log(percent); }), success: function (result) { console.log(result); }, }) } </script> </html>