如何在Vue.js中使用vue-resource检测文件上传进度?
使用vue-resource监听文件上传进度
嘿,我之前刚好也碰到过这个场景!其实vue-resource和axios一样支持上传进度监听,只是配置项的名称有点不同,我给你两种可行的方案:
方案一:使用配置项中的uploadProgress回调
这是最贴合vue-resource风格的写法,直接在请求的配置对象里指定uploadProgress函数就行,和axios的onUploadProgress逻辑完全一致:
// 假设你在Vue组件中,fd是已构建好的FormData对象 this.$http.post('/upload.php', fd, { uploadProgress: (event) => { // 计算上传进度百分比 const progressPercent = Math.round((event.loaded * 100) / event.total) // 把进度赋值给组件的data属性,用来驱动进度条 this.uploadProgress = progressPercent console.log(`当前上传进度:${progressPercent}%`) } }).then( (response) => { // 上传成功后的逻辑 console.log('文件上传完成!', response) }, (error) => { // 上传失败的错误处理 console.error('上传出错了', error) } )
这里的event对象就是XMLHttpRequest的进度事件对象,包含loaded(已上传字节数)和total(文件总字节数)两个核心属性,用来计算进度非常方便。
方案二:直接操作底层XMLHttpRequest对象
如果你的vue-resource版本比较旧,或者更习惯直接操作XHR对象,也可以这样写:
// 发起请求并获取请求实例 const uploadRequest = this.$http.post('/upload.php', fd) // 监听XHR的progress事件 uploadRequest.xhr.onprogress = (event) => { const progressPercent = Math.round((event.loaded * 100) / event.total) this.uploadProgress = progressPercent } // 处理请求结果 uploadRequest.then( (response) => console.log('上传成功'), (error) => console.error('上传失败') )
注意事项
- 确保你的vue-resource版本是v1.0及以上,旧版本可能没有
uploadProgress配置项。 - 后端接口需要正确处理FormData格式的文件上传,否则可能无法触发进度事件。
内容的提问来源于stack exchange,提问作者abu abu
相关产品推荐
相关产品推荐

