xhr 上传文件 带进度条 loading 实现方法

xhr 上传示例

//本地上传
let data = new FormData();
data.append('id',id);
data.append('filename',fid);
console.log('formData',data);
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
   if(xhr.readyState == 4 && xhr.status==200){
      if(xhr.responseText){
         var res = JSON.parse(xhr.responseText);
         res.forEach(function(v,i){
            window[fid+'_url'].push(v.src);
            window[fid+'_fname'].push(v.name);
         });
         // console.log('newurl',window[fid+'_url']);
         resolve(window[fid+'_url']);
      }else{
         resolve(window[fid+'_url']);
      }
   }else{
      $('#loadDiv').hide();
   }
};
xhr.open('POST','./upfile');
xhr.upload.onprogress = (e) => {
   if (e.lengthComputable) {
      $('#loadDiv').show();
      let percentComplete = e.loaded / e.total * 100;
      //这个地方可以处理进度条  
      console.log('上传进度',percentComplete);
      if(percentComplete == 100){
         $('#loadDiv').hide();
      }
   }
}
xhr.send(data)