Vue/js implements file stream download, file download progress monitoring

	/**
     * 文档下载(通过文档请求,直接下载文档)
     * url 请求路径
     * fileName 下载名称
     * size 文件大小
     */
    loadDown (url, fileName, size) {
    
    
      var _this = this
      var xhr = new XMLHttpRequest()
      xhr.open('GET', url, true) // 也可以使用POST方式,根据接口
      xhr.responseType = 'blob'
      xhr.onprogress = function (event) {
    
    
         // 用于监听下载进度,需要知道文件大小
         if (event.loaded === size) {
    
    
           _this.downloadLoading = false
         }        
      }
      xhr.onload = function () {
    
    
        if (this.status === 200) {
    
    
          var content = this.response
          var aTag = document.createElement('a')
          var blob = new Blob([content])
          aTag.download = fileName
          aTag.href = URL.createObjectURL(blob)
          aTag.click()
          URL.revokeObjectURL(blob)
        }
      }
      xhr.send()
    }
    /**
    *request请求,获取文件地址
    */
     async handlePreview (file) {
    
    
      var _this = this
      var xhr = new XMLHttpRequest()// 第一步:新建对象
      xhr.open('GET', file.url, true)// 第二步:打开连接  将请求参数写在url中
      xhr.send()// 第三步:发送请求  将请求参数写在URL中
      /**
         * 获取数据后的处理程序
         */
      xhr.onreadystatechange = function (res) {
    
    
        if (xhr.readyState === 4 && xhr.status === 200) {
    
    
          var str = xhr.responseText// 获取到json字符串,解析
          str = JSON.parse(str)        
          _this.loadDown(str.d, file.name)
        }
      }
    },

Guess you like

Origin blog.csdn.net/yuanbo_520/article/details/109381395