前端做下载文件功能(三种方法)

1.一般媒体文件下载

    downloadFile(url, filename) {
    
        //第二个参数是文件的名字,传参的时候要带上后缀
      const xhr = new XMLHttpRequest()
      xhr.open('GET', url, true)
      xhr.responseType = 'blob'
      xhr.onload = function() {
    
    
        if (this.status === 200) {
    
    
          const blob = this.response
          const $a = document.createElement('a')
          // blob.type = 'application/octet-stream';
          const fileUrl = URL.createObjectURL(blob)
          $a.href = fileUrl
          $a.download = filename
          $a.click()
          window.URL.revokeObjectURL(url)
        }
      }
      xhr.send()
    }

2.文档类的直接 window.open(url)

3.用js创建a标签

猜你喜欢

转载自blog.csdn.net/qq_45432996/article/details/113097247