Home Web Front-end uni-app uniapp implements progress bar upload

uniapp implements progress bar upload

May 22, 2023 pm 02:26 PM

With the popularity of mobile Internet, more and more applications need to upload files, such as avatars, photos, documents, etc. During the file upload process, users often need to wait for a period of time to complete the upload. At this time, the progress bar is a very good display method. In recent years, uniapp has become one of the popular frameworks for mobile development. This article will introduce how to use uniapp to implement the function of uploading files with a progress bar.

1. Prerequisite knowledge

Before studying this article in depth, you need to master the following skills:

  1. Basic usage of uniapp
  2. ajax How to use asynchronous requests
  3. Basic operations of file upload

2. Preparation

First of all, please make sure you have installed vue-cli, and then use vue-cli creates a uniapp project. Because this article mainly explains the implementation of the file upload function, it will not involve the implementation of other functions.

3. Implementation process

  1. Create file upload component and progress bar component

1.1 Create file upload component

In the uniapp framework , the file upload function can be easily implemented by using the uni-upload control. Create an Upload component in the components folder, the code is as follows:

<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>
Copy after login

1.2 Create a progress bar component

The progress bar function can be easily implemented using the uni-progress component in the uniui component library . Create a ProgressBar component under the components folder, the code is as follows:

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

<script>
export default {
  name: "ProgressBar",
  props: {
    percent: {
      type: Number,
      default: 0
    }
  }
};
</script>
Copy after login
  1. Implement the upload progress bar function

2.1 Get the file upload progress

File upload During the process, the server will return the upload progress accordingly. We can obtain the upload progress by listening to the progress event of the XMLHttpRequest object. Add the following code in the Upload component:

<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>
Copy after login

In the uploadFile method, use the XMLHttpRequest object to create a POST request, and listen to the progress event of the upload attribute of the XMLHttpRequest object. Whenever an upload event occurs, the updateProgress method will be triggered to update the percent data in the component.

2.2 Cancel file upload

During the file upload process, the user may need to cancel the upload operation. In order to support the cancellation operation, we need to add a cancel button to the Upload component, and also need to add upload cancellation logic to the uploadFile method.

<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>
Copy after login

When the user clicks the cancel upload button, the cancelUpload method will be executed. At this time, the upload operation will be canceled by calling the abort method of the XMLHttpRequest object.

4. Summary

In this article, we implemented a file upload progress bar function by using the uniapp framework combined with components in the uniui component library. With the onprogress event of the XMLHttpRequest object, we can obtain the upload progress in time and cancel the upload operation by calling the abort method of the XMLHttpRequest object. This small feature can not only increase the user experience of the application, but also help developers better understand the use of XMLHttpRequest objects and the basic principles of the uniapp framework.

The above is the detailed content of uniapp implements progress bar upload. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the different types of testing that you can perform in a UniApp application? What are the different types of testing that you can perform in a UniApp application? Mar 27, 2025 pm 04:59 PM

The article discusses various testing types for UniApp applications, including unit, integration, functional, UI/UX, performance, cross-platform, and security testing. It also covers ensuring cross-platform compatibility and recommends tools like Jes

How can you reduce the size of your UniApp application package? How can you reduce the size of your UniApp application package? Mar 27, 2025 pm 04:45 PM

The article discusses strategies to reduce UniApp package size, focusing on code optimization, resource management, and techniques like code splitting and lazy loading.

What debugging tools are available for UniApp development? What debugging tools are available for UniApp development? Mar 27, 2025 pm 05:05 PM

The article discusses debugging tools and best practices for UniApp development, focusing on tools like HBuilderX, WeChat Developer Tools, and Chrome DevTools.

How can you use lazy loading to improve performance? How can you use lazy loading to improve performance? Mar 27, 2025 pm 04:47 PM

Lazy loading defers non-critical resources to improve site performance, reducing load times and data usage. Key practices include prioritizing critical content and using efficient APIs.

How can you optimize images for web performance in UniApp? How can you optimize images for web performance in UniApp? Mar 27, 2025 pm 04:50 PM

The article discusses optimizing images in UniApp for better web performance through compression, responsive design, lazy loading, caching, and using WebP format.

What are some common patterns for managing complex data structures in UniApp? What are some common patterns for managing complex data structures in UniApp? Mar 25, 2025 pm 02:31 PM

The article discusses managing complex data structures in UniApp, focusing on patterns like Singleton, Observer, Factory, and State, and strategies for handling data state changes using Vuex and Vue 3 Composition API.

What are computed properties in UniApp? How are they used? What are computed properties in UniApp? How are they used? Mar 25, 2025 pm 02:23 PM

UniApp's computed properties, derived from Vue.js, enhance development by providing reactive, reusable, and optimized data handling. They automatically update when dependencies change, offering performance benefits and simplifying state management co

How does UniApp handle global configuration and styling? How does UniApp handle global configuration and styling? Mar 25, 2025 pm 02:20 PM

UniApp manages global configuration via manifest.json and styling through app.vue or app.scss, using uni.scss for variables and mixins. Best practices include using SCSS, modular styles, and responsive design.

See all articles