0
点赞
收藏
分享

微信扫一扫

通过后端返回的url,前端怎么把文件下载下来

// 点击下载文件
    downloadFile(file) {
        // 音视频下载
        if (file.url.indexOf('http://') >=0 || file.url.indexOf('https://') >= 0) {
          let handleUrl = ''
          if (location.protocol === 'https:') {
            handleUrl = file.url.replace('http://', 'https://')
          } else {
            handleUrl = file.url
          }
          const loading = this.$loading({
            lock: true,
            text: '正在下载中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          var xhr = new XMLHttpRequest()
          xhr.open("GET", handleUrl, true)
          xhr.responseType = 'blob'
          xhr.onload = function(e){
            if (e.target.readyState === 4 && e.target.status === 200) {
                let blob = this.response
                // 转换一个blob链接
                let u = window.URL.createObjectURL(new Blob([blob]))
                let a = document.createElement('a');
                a.download = file.fileName
                a.href = u
                a.style.display = 'none'
                document.body.appendChild(a)
                a.click()
                a.remove()
                loading.close()
            }
          }
          xhr.send()
        }
    },

注意点:名字一定要带上后缀格式


举报

相关推荐

0 条评论