🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
这个上传进度是通知XMLHttpRequest的upload.onprogress事件来监听的,代码如下 ~~~ var xhr = XMLHttpRequest(); xhr.upload.onprogress = function(e) { var loaded = e.loaded, total = e.total, progress = Math.floor(loaded/total*100); console.log(progress); } ~~~ 示例效果 ![](https://box.kancloud.cn/39b78513b7ebd99e51ca484c68b495fd_340x392.gif) 代码 ~~~ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>文件上传</title> <script type="text/javascript" src="vue.min.js"></script> </head> <body> <div id="app"> <fieldset style="float: left;"> <legend>上传</legend> <input type="file" name="avatar" v-on:change="selectedShow"> <button type="button" v-on:click="upload">上传</button> <div v-show="progressShow"> <progress v-model="progress" max="100"></progress> <div>{{ loaded }} / {{ total }}</div> <ul> <li v-for="item in imgInfo">{{ item.name }} : {{ item.value | default }}</li> </ul> </div> </fieldset> <img style="display: block;clear: both;" v-bind:src="imgSrc" alt=""> </div> <script> var app = new Vue({ el: '#app', data: { loaded: 0, // 已上传大小 total: 0, // 总大小 progress: 0, // 上传进度 imgSrc: '', // 图片src imgFile: '', // 图片文件 imgInfo: [], // 图片信息 progressShow: false // 是否显示进度条 }, filters: { default: function(v) { if(v!==undefined && v==='') { return '--'; } else { return v; } } }, methods: { // 选择图片显示 selectedShow: function(e) { this.imgFile = e.target.files[0]; this.imgSrc = window.URL.createObjectURL(this.imgFile); }, // 上传 upload: function() { this.imgInfo = []; this.loaded = 0; this.total = 0; this.progress = 0; if(this.imgFile) { // FormData var formData = new FormData(); formData.append('avatar', this.imgFile); var xhr = new XMLHttpRequest(); xhr.responseType = 'json'; // 状态改变事件 xhr.onreadystatechange = function() { if(xhr.readyState===4 && xhr.status===200) { var data = xhr.response; console.log(data); this.imgInfo.push({ "name": "名称", "value": data.name }); this.imgInfo.push({ "name": "类型", "value": data.type }); this.imgInfo.push({ "name": "尺寸", "value": data.size }); } }.bind(this); // 进度事件 xhr.upload.onprogress = function(e) { this.progressShow = true; var loaded = e.loaded, total = e.total, progress = Math.floor(loaded/total*100); this.loaded = loaded; this.total = total; this.progress = progress; }.bind(this); xhr.open('post', 'demo.php'); xhr.send(formData); } else { alert('请先选择图片文件~'); } } } }); </script> </body> </html> ~~~ 对应的demo.php代码 ~~~ <?php $avatar = $_FILES['avatar']; echo json_encode($avatar); ~~~ 附加 FormData的介绍 https://segmentfault.com/a/1190000006716454