Programing

Vue 및 Axios가 포함된 진행 표시줄

c10106 2022. 4. 10. 22:57
반응형

Vue 및 Axios가 포함된 진행 표시줄

이미지 업로더를 만들고 있는데, 파일이 선택되면 증분을 시작하는 진행 표시줄을 표시하려고 해.

Axios를 사용하여 백엔드에 액세스하고 다음과 같이 설정한다.

const BASE_URL = 'http://localhost:3000';

function uploadImage(data, listingId) {
  const url = `${BASE_URL}/listings/${listingId}/images`;
  let config = {
    onUploadProgress(progressEvent) {
      var percentCompleted = Math.round((progressEvent.loaded * 100) /
        progressEvent.total);
      return percentCompleted;
    },
  };
  return axios.post(url, data, config).
      then(x => x.request.response).
      catch(error => error);
}

에 액세스하려면percentCompleted아래 Vue 쪽에서?

inputDidChange(e) {
  let inputData = e.target.files[0];
  var formData = new FormData();
  formData.append('image', inputData);
  uploadImage(formData, this.listingId).
    then((x) => {
      var xParsed = JSON.parse(x);
      this.newFile = xParsed.image.image.url;
      this.files.push(this.newFile);
      console.log('success');
  });
},

콜백(callback)을 고객에게 전달uploadImage기능을 발휘하다

function uploadImage(data, listingId, onProgress){
  const url = `${BASE_URL}/listings/${listingId}/images`;
  let config = {
     onUploadProgress(progressEvent) {
      var percentCompleted = Math.round((progressEvent.loaded * 100) /
        progressEvent.total);

      // execute the callback
      if (onProgress) onProgress(percentCompleted)

      return percentCompleted;
    },
  };
  return axios.post(url, data, config).
      then(x => x.request.response).
      catch(error => error);
}

그리고 부에 방식으로 통과한다.

methods:{
  onProgress(percent){
    //update vue
  },
  inputDidChange(e) {
    let inputData = e.target.files[0];
    var formData = new FormData();
    formData.append('image', inputData);
    uploadImage(formData, this.listingId, this.onProgress).
      then((x) => {
        var xParsed = JSON.parse(x);
        this.newFile = xParsed.image.image.url;
        this.files.push(this.newFile);
        console.log('success');
    });
  },
}

참조URL: https://stackoverflow.com/questions/45403463/progress-bar-with-vue-and-axios

반응형