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!

The article discusses debugging strategies for mobile and web platforms, highlighting tools like Android Studio, Xcode, and Chrome DevTools, and techniques for consistent results across OS and performance optimization.

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

The article discusses end-to-end testing for UniApp applications across multiple platforms. It covers defining test scenarios, choosing tools like Appium and Cypress, setting up environments, writing and running tests, analyzing results, and integrat

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 common performance anti-patterns in UniApp development, such as excessive global data use and inefficient data binding, and offers strategies to identify and mitigate these issues for better app performance.

The article discusses using profiling tools to identify and resolve performance bottlenecks in UniApp, focusing on setup, data analysis, and optimization.

The article discusses strategies for optimizing network requests in UniApp, focusing on reducing latency, implementing caching, and using monitoring tools to enhance application performance.

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


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

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software