我是Vuejs的新手。请帮我 。 这是我的LevelApi类,用于处理数据库中Level对象的CRUD操作。此类的create函数获取表单数据并将其发布到Node js Api,然后返回响应。在用户提交表单时,在我的AddLevel组件中,我调用此方法并将包含要上传到mongodb中Level集合的一个文件的表单数据传递。
import axios from 'axios'
const API_URL = 'http://example:8080/api/level/'
export default class LevelApi {
create (formData) {
return axios.post('http://example.com/api/level/', formData, {
headers: { 'Authorization': 'Bearer ' + localStorage.getItem('jwt'), 'content-type': 'multipart/form-data' },
onUploadProgress: function (progressEvent) {
this.uploadPercentage = parseInt(Math.round((progressEvent.loaded * 100) / progressEvent.total))
}.bind(this)
})
}
下面是我的AddLevel组件。
<template>
<div>
<form>
<div class="form-group">
<label>please choose image for this level</label>
<input type="file" id="file" ref="myFiles" @change="previewFiles">
</div>
<button @click.prevent="storeLevel">add level</button>
</form>
<progress-bar v-bind:val="getPercentage" max="100" :text="uploadPercentageWithPercent"></progress-bar>
</div>
</div>
</template>
<script>
import LevelApi from '../../services/api/level/LevelApi' // importing the LevelApi class that I mentioned above
const levelApi = new LevelApi()
export default {
name: 'AddLevel',
data () {
return {
files: {},
uploadPercentage: 0,
}
},
methods: {
storeLevel () {
var formData = new FormData()
formData.append('file', this.files)
levelApi.create(formData).then((response)=>{
console.log(response.data)
});
},
previewFiles () {
this.files = this.$refs.myFiles.files[0]
},
},
computed: {
uploadPercentageWithPercent () {
return this.uploadPercentage.toString().concat('%')
},
getPercentage () {
return this.uploadPercentage
},
resetPercentage () {
this.uploadPercentage = 0
}
},
}
</script>
<style scoped>
</style
一切正常,文件已上传,但进度条未显示uploadPercentage数据。但是当我在控制台上记录此uploadPercentage时,它会增长到100%。我将代码更改为以下内容,问题得以解决。下面的代码现在不使用ApiLevel类。现在进度条显示了上载的百分比。我的ApiLevel类出了什么问题。尽管console.log函数中的uploadPercentage值发生了变化,为什么进度条不显示上载百分比。
var formData = new FormData()
formData.append('file', this.files)
this.$http.post('http://example.com/api/level/', formData, {
headers: { 'Authorization': 'Bearer ' + localStorage.getItem('jwt'), 'content-type': 'multipart/form-data' },
onUploadProgress: function (progressEvent) {
this.uploadPercentage = parseInt(Math.round((progressEvent.loaded * 100) / progressEvent.total))
}.bind(this)
}).then((response) => {
}
})