Home > Back-end >  VueJS Axios onUploadProgress inside the component from service
VueJS Axios onUploadProgress inside the component from service

Time:05-05

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

CodePudding user response:

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);
}

CodePudding user response:

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);
  })
  • Related