>  기사  >  웹 프론트엔드  >  uniapp은 진행률 표시줄 업로드를 구현합니다.

uniapp은 진행률 표시줄 업로드를 구현합니다.

WBOY
WBOY원래의
2023-05-22 14:26:382454검색

모바일 인터넷의 인기로 인해 점점 더 많은 애플리케이션에서 아바타, 사진, 문서 등과 같은 파일을 업로드해야 합니다. 파일 업로드 과정에서 사용자는 업로드를 완료하기 위해 일정 시간을 기다려야 하는 경우가 많습니다. 이때 진행률 표시줄은 매우 좋은 표시 방법입니다. 최근 몇 년 동안 uniapp은 모바일 개발을 위한 인기 있는 프레임워크 중 하나로 자리 잡았습니다. 이 기사에서는 uniapp을 사용하여 진행률 표시줄이 있는 파일 업로드 기능을 구현하는 방법을 소개합니다.

1. 전제 지식

이 기사를 자세히 공부하기 전에 다음 기술을 숙지해야 합니다.

  1. uniapp의 기본 사용법
  2. ajax 비동기 요청 사용 방법
  3. 파일 업로드의 기본 작업

2. 준비 작업

먼저 vue-cli가 설치되어 있는지 확인한 후 vue-cli를 사용하여 uniapp 프로젝트를 생성합니다. 이 글에서는 주로 파일 업로드 기능의 구현을 설명하므로 다른 기능의 구현은 포함하지 않습니다.

3. 구현 프로세스

  1. 파일 업로드 컴포넌트 및 진행률 표시줄 컴포넌트 생성

1.1 파일 업로드 컴포넌트 생성

uniapp 프레임워크에서는 uni-upload 컨트롤을 사용하여 파일 업로드 기능을 쉽게 구현할 수 있습니다. 구성 요소 폴더 아래에 업로드 구성 요소를 생성합니다. 코드는 다음과 같습니다.

<template>
  <view>
    <uni-upload class="upload-btn" :upload-url="uploadUrl" />
  </view>
</template>

<script>
export default {
  name: "Upload",
  props: {
    uploadUrl: {
      type: String,
      default: ""
    }
  }
};
</script>

<style lang="scss">
.upload-btn {
  width: 100px;
  height: 50px;
  background-color: #409eff;
  color: #fff;
  border: none;
  border-radius: 4px;
  text-align: center;
  line-height: 50px;
  cursor: pointer;
  user-select: none;
}
</style>

1.2 진행률 표시줄 구성 요소 만들기

uniui 구성 요소 라이브러리의 uni-progress 구성 요소를 사용하면 진행률 표시줄 기능을 쉽게 구현할 수 있습니다. 구성 요소 폴더 아래에 ProgressBar 구성 요소를 만듭니다. 코드는 다음과 같습니다.

<template>
  <view>
    <uni-progress :percent="percent" />
  </view>
</template>

<script>
export default {
  name: "ProgressBar",
  props: {
    percent: {
      type: Number,
      default: 0
    }
  }
};
</script>
  1. 업로드 진행률 표시줄 기능 구현

2.1 파일 업로드 진행률 가져오기

파일 업로드 프로세스 중에 서버는 이에 따라 업로드 진행률을 반환합니다. . XMLHttpRequest 객체의 진행 이벤트를 수신하여 업로드 진행 상황을 얻을 수 있습니다. 업로드 구성 요소에 다음 코드를 추가합니다.

<template>
  <view>
    <uni-upload class="upload-btn" :upload-url="uploadUrl" @change="onChange" />
    <ProgressBar :percent="percent" />
  </view>
</template>

<script>
import ProgressBar from "../components/ProgressBar";

export default {
  name: "Upload",
  props: {
    uploadUrl: {
      type: String,
      default: ""
    }
  },
  components: {
    ProgressBar
  },
  data() {
    return {
      percent: 0,
      uploadRequest: null
    };
  },
  methods: {
    onChange(e) {
      const file = e.target.files[0];
      if (!file) return;
      this.uploadRequest = this.uploadFile(file);
    },
    uploadFile(file) {
      const formData = new FormData();
      formData.append("file", file);
      const xhr = new XMLHttpRequest();
      xhr.open("POST", this.uploadUrl);
      xhr.upload.addEventListener("progress", this.updateProgress);
      xhr.send(formData);
      return xhr;
    },
    updateProgress(e) {
      const percent = ((e.loaded / e.total) * 100).toFixed(2);
      this.percent = percent;
    }
  }
};
</script>

uploadFile 메서드에서 XMLHttpRequest 개체를 사용하여 POST 요청을 생성하고 XMLHttpRequest 개체의 업로드 속성에 대한 진행 이벤트를 수신합니다. 업로드 이벤트가 발생할 때마다 updateProgress 메소드가 트리거되어 구성 요소의 백분율 데이터를 업데이트합니다.

2.2 파일 업로드 취소

파일 업로드 프로세스 중에 사용자가 업로드 작업을 취소해야 할 수도 있습니다. 취소 작업을 지원하려면 업로드 구성 요소에 취소 버튼을 추가해야 하며 uploadFile 메서드에 업로드 취소 논리도 추가해야 합니다.

<template>
  <view>
    <uni-upload class="upload-btn" :upload-url="uploadUrl" @change="onChange" />
    <ProgressBar :percent="percent" />
    <view class="controls">
      <view class="btn" @click="cancelUpload">取消上传</view>
    </view>
  </view>
</template>

<script>
import ProgressBar from "../components/ProgressBar";

export default {
  name: "Upload",
  props: {
    uploadUrl: {
      type: String,
      default: ""
    }
  },
  components: {
    ProgressBar
  },
  data() {
    return {
      percent: 0,
      uploadRequest: null
    };
  },
  methods: {
    onChange(e) {
      const file = e.target.files[0];
      if (!file) return;
      this.uploadRequest = this.uploadFile(file);
    },
    uploadFile(file) {
      const formData = new FormData();
      formData.append("file", file);
      const xhr = new XMLHttpRequest();
      xhr.open("POST", this.uploadUrl);
      xhr.upload.addEventListener("progress", this.updateProgress);
      xhr.send(formData);
      return xhr;
    },
    updateProgress(e) {
      const percent = ((e.loaded / e.total) * 100).toFixed(2);
      this.percent = percent;
    },
    cancelUpload() {
      if (this.uploadRequest) {
        this.uploadRequest.abort();
      }
    }
  }
};
</script>

<style lang="scss">
.controls {
  margin-top: 10px;
}

.btn {
  background-color: #ff4949;
  color: #fff;
  width: 100px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  border-radius: 4px;
  cursor: pointer;
  user-select: none;
}
</style>

사용자가 업로드 취소 버튼을 클릭하면 cancelUpload 메소드가 실행됩니다. 이때 XMLHttpRequest 객체의 abort 메소드를 호출하여 업로드 작업이 취소됩니다.

4. 요약

이 글에서는 uniui 컴포넌트 라이브러리의 컴포넌트와 결합된 uniapp 프레임워크를 사용하여 파일 업로드 진행률 표시줄 기능을 구현했습니다. XMLHttpRequest 객체의 onprogress 이벤트를 사용하면 XMLHttpRequest 객체의 abort 메서드를 호출하여 업로드 진행 상황을 적시에 얻을 수 있고 업로드 작업을 취소할 수 있습니다. 이 작은 기능은 애플리케이션의 사용자 경험을 향상시킬 수 있을 뿐만 아니라 개발자가 XMLHttpRequest 개체의 사용과 uniapp 프레임워크의 기본 원칙을 더 잘 이해하는 데 도움이 됩니다.

위 내용은 uniapp은 진행률 표시줄 업로드를 구현합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.