问题描述
服务器发送和响应一切正常。
问题是我不知道如何从导出的对象中获取进度百分比(正确计算)。
我的文件upload.js:
import axios from 'axios'
const baseUrl = 'http://localhost:80/upload.PHP'
const config = {
Headers: {'Content-Type': 'multipart/form-data'},onUploadProgress: progressEvent => {
return parseInt(Math.round((progressEvent.loaded / progressEvent.total) * 100))
}
}
export default {
send (data) {
return axios.post(baseUrl,data,config)
}
}
我的 Vue 组件:
<template>
<div>
<label>File:</label>
<input type="file" id="file" ref="file" @change="changeFile()" />
<button @click="submit()">Upload</button>
<br />
<progress max="100" :value.prop="uploadPercentage"></progress>
</div>
</template>
<script>
import upload from '../services/upload.js'
export default {
name: 'Upload',data: () => ({
file: null,uploadPercentage: 0
}),methods: {
submit () {
const formData = new FormData()
formData.append('file',this.file)
upload.send(formData)
.then(res => {
console.log(res.data)
})
.catch(() => {
console.log('Failure')
})
},changeFile () {
this.file = this.$refs.file.files[0]
}
}
}
</script>
如何从组件submit方法中获取onUploadProgress发送的信息以更新数据uploadPercentage? >
谢谢。
问候。
解决方法
您需要将一个函数传递给稍后将调用的发送操作。
见下面的例子
const config = {
Headers: {'Content-Type': 'multipart/form-data'},onUploadProgress: progressEvent => {
var progress= parseInt(Math.round((progressEvent.loaded / progressEvent.total) * 100));
if (config.onProgress)
config.onProgress(progress);
}
}
export default {
send (data,onProgress) {
config.onProgress= onProgress;
return axios.post(baseUrl,data,config)
}
}
然后你上传的代码将是
upload.send(formData,(pogress)=>{
// Update your uploadPercentage here
})
.then(res => {
console.log(res.data)
})
.catch(() => {
console.log('Failure')
})