'VueJS Axios onUploadProgress inside the component from service
I am trying to create a progress bar in vuejs ... however, all the tutorials are calling directly axios inside the component... my setup is a bit more ... different :)
what I have in component is this upload method
uploadPhotos() {
const formData = new FormData();
this.gallery_photos.forEach(photo => {
formData.append(`photo_${photo.name}`, photo);
});
PhotoService.uploadPhotos(this.gallery.id_gallery, formData, callback => {
console.log(callback);
})
.then(() => {
console.log("OK");
})
.catch(error => {
console.log(error);
});
}
and this is my service
uploadPhotos(id, photos) {
const config = {
onUploadProgress: function (progressEvent) {
const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
console.log(percentCompleted);
}
};
return axios.post(`galleries/${id}/photos`, photos, { headers: authHeader() }, config);
}
However, from neither of those I am getting the input ... what am I missing? :(
Everything else is working fine... I am getting the files on the server side so I can process them correctly.. I just have no idea what the onUploadProgress is not doing anything
Solution 1:[1]
Might need to combine the headers into the config
uploadPhotos(id, photos) {
const config = {
onUploadProgress: function (progressEvent) {
const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
console.log(percentCompleted);
},
headers: authHeader()
};
return axios.post(`galleries/${id}/photos`, photos, config);
}
Solution 2:[2]
You need to add a callback parameter to your function and trigger it:
uploadPhotos(id, photos, cb) {
const config = {
onUploadProgress: function (progressEvent) {
const percentCompleted = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
);
cb(percentCompleted); // <== you can pass here whatever you want
},
};
return axios.post(
`galleries/${id}/photos`,
photos,
{ headers: authHeader() },
config
);
}
Now you will see your data:
PhotoService.uploadPhotos(this.gallery.id_gallery, formData, percent => {
console.log(percent);
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Guido Faecke |
| Solution 2 | bill.gates |
