点击按钮,下载文件

实现文件的下载功能

1、使用a标签

直接下载仅适用于浏览器无法识别的文件
如果是浏览器支持的文件格式,如html、jpg、png、pdf等,则不会触发文件下载,而是直接被浏览器解析并展示

    <a
      href="http://xxxxxx.rar"
      download
    >
      下载压缩包,默认a连接a
    >
    <a
      href="http://xxxxxx.jpg"
      download
    >
      下载图片,默认a连接a
    >

2、location.href和window.open

对于一些浏览器无法识别的文件格式,可以直接再浏览器地址栏输入url即可触发浏览器的下载功能。
浏览器可以识别的会自动打开预览界面

      window.location.href =
        'xxxxx.rar'

      window.open(
        'http://resource.teld.cc/teldimage/142/c7c5db8e52e748b8affe35625dbdc8ee.jpg'
      )

3、文件流,原生Ajax

    function downloadFile(url, fileName) {
      var x = new XMLHttpRequest();
      x.open("GET", url, true);
      x.responseType = 'blob';
      x.onload = function (e) {
        console.log('x.response', x.response)
        var url = window.URL.createObjectURL(x.response)
        var a = document.createElement('a');
        a.href = url;
        a.download = fileName;
        a.click();
      }
      x.send();
    }

4、文件流,axios

第二层axios 返回的就是Blob 格式的数据类型 所以可以不用再 new Blob ,直接用window.URL.createObjectURL(res.data) 就可以

  <button id="download">下载文件22222button>
  
 <script>
    let downloadDom = document.querySelector('#download')
    downloadDom.addEventListener('click', function (e) {
      axios({ url: 'http://127.0.0.1:8000/fileDownload' }).then(res => {
          // 第一层的res是获取到了一个文件的 url 地址
        axios({ url: res.data.url, responseType: "blob" }).then(res => {
          console.log('第二层axios', res)
          // const blob = new Blob([res.data], {
          //   // type: 'application/x-rar-compressed;charset=utf-8'
          // })
          // console.log(blob)
          let a = document.createElement('a')
          a.style = 'display: none' // 创建一个隐藏的a标签
          a.download = '自定义.rar'
          // a.href = url
          // a.href = window.URL.createObjectURL(blob)
          a.href = window.URL.createObjectURL(res.data)
          document.body.appendChild(a)
          a.click() // 触发a标签的click事件
          document.body.removeChild(a)
        })
      })
    })
  script>

点击按钮,下载文件_第1张图片

# 别人的版本
function downloadFile(data,fileName){
    // data为blob格式
    var blob = new Blob([data]);
    var downloadElement = document.createElement('a');
    var href = window.URL.createObjectURL(blob);
    downloadElement.href = href;
    downloadElement.download = fileName;
    document.body.appendChild(downloadElement);
    downloadElement.click();
    document.body.removeChild(downloadElement);
    window.URL.revokeObjectURL(href); // 释放URL对象
}

5、参考连接

1、掘金前端实现文件下载(含多文件下载思路)的几种方法
2、Blob MDN

你可能感兴趣的:(项目,js,javascript,vue.js,前端)