uniapp implements progress bar upload
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:
- Basic usage of uniapp
- ajax How to use asynchronous requests
- 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
- 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>
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>
- 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>
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>
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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

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

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.

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

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.

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

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.
