Home  >  Article  >  Web Front-end  >  How to add a progress bar to upload images in axios

How to add a progress bar to upload images in axios

php中世界最好的语言
php中世界最好的语言Original
2018-04-14 10:23:443775browse

This time I will show you how to add a progress bar to uploaded images in axios. What are the precautions for axios to add a progress bar to uploaded images? The following is a practical case. Let’s take a look. take a look.

Axios is a promise-based HTTP library that can be used in browsers and

node.js.

Features

Create XMLHttpRequests

from the browser Create http request from node.js

Support Promise API

Intercepting requests and responses

Convert request data and response data

Cancel request

Automatically convert JSON data

Client supports defense against XSRF

Let me introduce to you how to use axios to implement the progress bar function of uploading pictures. The specific content is as follows:

In a recent project, a mobile phone page needs to upload up to dozens of pictures. Although the photos are compressed, they are still very large in the end. If the network card is used, the upload time is very poor. If it keeps loading, the user will I don’t know how much I have uploaded. In order to display the upload progress more intuitively, it is best to display the progress bar and the upload percentage;

The project uses the vuejs framework, and mint-ui is used as the UI framework; the request is axios, which is officially recommended by vue (really powerful); the axios official introduced the use of native upload processing progress

event (specific reference Here, here is the official introduction of axios in Chinese):

 onUploadProgress: function (progressEvent) {
  // 对原生进度事件的处理
 },
 Because of the use of vuejs, the data requests from the interface need to be managed uniformly to facilitate management. If placed in each component, it will be inconvenient for future maintenance and management; in the reqwest.js file, an uploadPhoto method is defined, which has three parameters, namely parameters, and two

callback functions , the parameters are the parameters we need to upload the image; the first callback function is to obtain the data contained in the upload progress, and the second callback is to obtain the data returned by the background if the upload is successful or failed; to perform the next operation of the page.

 uploadPhoto(payload,callback1,callback2){
    axios({
      url:BASE_URL + '/handler/material/upload',
      method:'post',
      onUploadProgress:function(progressEvent){ //原生获取上传进度的事件
        if(progressEvent.lengthComputable){
          //属性lengthComputable主要表明总共需要完成的工作量和已经完成的工作是否可以被测量
          //如果lengthComputable为false,就获取不到progressEvent.total和progressEvent.loaded
          callback1(progressEvent);
        }
      },
      data:payload
    }).then(res =>{
      callback2(res.data);
    }).then(error =>{
      console.log(error)
    })
  }
Use the Progress component in the mint-ui component and define the variable "precent" in the component in the data method. The variable is of type number. When defining, pay attention;

<mt-progress :value="precent" :bar-height="10">
   <p slot="end">{{Math.ceil(precent)}}%</p>
  </mt-progress>
Import the reqwest.js file, get the uploadPhoto method, and use the $nextTick attribute to update the page in real time based on the upload progress.

const _this = this;
API.uploadPhoto(fd,(res) =>{
 let loaded = res.loaded,
   total = res.total;
   _this.$nextTick(() =>{
    _this.precent = (loaded/total) * 100;
   })
},(res) =>{
  if(res.code === '200'){
    MessageBox.alert('图片上传成功').then(action => {
     console.log('ok');
    });
  }
})
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How to optimize the JSON data grouping of JS

ajax directly changes the state and deletes the non-refresh state

The above is the detailed content of How to add a progress bar to upload images in axios. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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