如何把文件流转化为文件下载?

使用浏览器的window.URL.createObjectURL(文件流)转化为url链接,然后借助a标签进行下载;
注意:window.URL.createObjectURL生成的是blod链接,该链接是浏览器生成的,只限于同一个页面或者同一个文档中使用,比如像vue的项目,只能在项目当中使用该链接下载,不能在别的项目上下载;

<!DOCTYPE html>
<html lang="zh">

<head>
  <meta charset="utf-8">
  <title>文件下载</title>
</head>

<body>
  <input type="file" onchange="inputChange()" id="file">
  <button onclick="downLoad()">下载</button>
</body>

<script>
  let file = {
      
      }
  function inputChange(val) {
      
      
    let fileDom = document.getElementById('file')
    file = fileDom.files[0]
  }

  function downLoad() {
      
      
    let url = window.URL.createObjectURL(file)
    let link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    link.setAttribute('download', '文件下载') // 给a设置download属性,属性值为文件名
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  }
</script>

</html>

猜你喜欢

转载自blog.csdn.net/m0_50441807/article/details/128823463
今日推荐