Home  >  Article  >  Web Front-end  >  How to use axios to upload pictures with a progress bar function

How to use axios to upload pictures with a progress bar function

亚连
亚连Original
2018-06-19 11:55:401816browse

Axios is a promise-based HTTP library that can be used in browsers and node.js. This article mainly introduces the use of axios to implement the progress bar of uploading images. Friends who need it can refer to it

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

Features

Create XMLHttpRequests from the browser

Create http requests from node.js

Support Promise API

Interception of 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 The mobile page needs to upload dozens of pictures at most. Although the pictures 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 not know how much he has 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, mint-ui as the UI framework; the request is axios officially recommended by vue (Really powerful); Axios officially introduces the use of native upload processing progress events (refer to here for details, here is the Chinese axios official introduction):

 onUploadProgress: function (progressEvent) {
  // 对原生进度事件的处理
 },

Because vuejs is used, for data requests from the interface, Convenient management requires unified 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. This method has three parameters, namely parameters and two callback functions. The parameters are what we want to upload. The required parameters of 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 step of the page operation.

 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 in the component in the data method. The variable is of type number. When defining, pay attention;


   

{{Math.ceil(precent)}}%

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');
    });
  }
})

According to the above method, the upload progress and percentage display of the image are basically realized. The rest is the UI, which can be customized according to your own personality to achieve your perfect needs...

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

How to implement random layout waterfall flow in ionic3

How to use Redux in React projects (detailed tutorial)

How to realize automatic numerical increase in JavaScript

How to use Swiper to realize the use of paginator

How to use Bus in Vue component communication

How to implement sensitive text prompts in Angular

How to implement hidden display in Angular

The above is the detailed content of How to use axios to upload pictures with a progress bar function. 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