本篇文章给大家带来的内容是关于js如何获取文件上传进度?js获取文件上传进度的代码,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
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>
相关文章推荐:
如何使用原生javascript实现轮播图?代码详解
js取整数、取余数的案例详解(附代码)
【js】:检测用户输入、文本框默认样式设置、设计表格样式实现全选反选
以上就是js如何获取文件上传进度?js获取文件上传进度的代码的详细内容。