Axios en Vue realiza la descarga de transmisión de archivos y supervisa el progreso de la descarga

Axios envía una solicitud por correo o recibe

/**
  * post请求下载
  */
 postDown(){
    
    
   // post||get
   axios.post(
     url,
     data, // body
     {
    
    
       responseType:'blob',
       onDownloadProgress:function(event){
    
     // 下载进度监听
         if(event.loaded===event.total){
    
    
           // 下载完成 loading = true
         }
       }
     }
   ).then(res=> {
    
    
     if(res.status===200){
    
    
       var fileName = res.headers['filename']// 需要后台返了filename
       var suffix = 'zip'
       if(fileName){
    
    
         var arr =fileName.split('.')
         suffix = arr[arr.length-1]
       }
       var content = res.data
       if(content.size<1){
    
    
         // 文件不存在
         this.$message({
    
    type:'info',message:'文件不存在'})
         return 
       }
       var blob = new Blob([content])
       fileName = 'timestamp.'+suffix
       this.downFile(null, blob, fileName)
     }
   }).catch(error=>{
    
    
     console.log(error)
   })
   
 },

Generar una etiqueta para ejecutar la descarga

/**
 * 生成下载标签,执行下载
 */
downFile(url, blob, fileName){
    
    
  var aTag = document.createElement('a')
  if(url){
    
    
    aTag.href = url
  }
  if(blob){
    
    
     aTag.href = URL.createObjectURL(blob)
  }
  if(fileName){
    
    
    aTag.download = fileName
  }
  aTag.click()
  URL.revokeObjectURL(aTag.href)
}

Supongo que te gusta

Origin blog.csdn.net/yuanbo_520/article/details/124929354
Recomendado
Clasificación