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 andnode.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 XSRFLet 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 progressevent (specific reference Here, here is the official introduction of axios in Chinese):
onUploadProgress: function (progressEvent) { // 对原生进度事件的处理 },
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) }) }
<mt-progress :value="precent" :bar-height="10"> <p slot="end">{{Math.ceil(precent)}}%</p> </mt-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'); }); } })
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!