大家都知道 a 标签是超链接,点击会跳转至 href 指定的地址。
当我们给 a 标签加上 download 属性后,则会去 href 指定的url下载文件(这里一定是同源的)
new Blob() 存放二进制资源
window.URL.createObjectURL() 会将 Blob存放的二进制资源转为url地址,如此而已
思路 :
1. 首先通过 document.createElement('a') 创建一个a标签 用 link 来接受
2. 通过 link.setAttribute('download', 'filename.html') 或者 直接 link.download = 'filename.html' 去给 a 标签添加 download 属性
3. 通过 window.URL.createObjectURL 将 blob二进制资源 转为 url地址并赋给link.href
4. 然后 执行 link.click() 即可下载
demo1
let html = `
  <div>
    <div>
      <p style="color: red;font-size: 20px;">张三</p>
    </div>
  </div>
`
const link = document.createElement('a')
link.setAttribute('download', 'zhangsan.html')
// link.download = 'zhangsan.html'
link.href = window.URL.createObjectURL(new Blob([html], { type: 'text/html' }))
link.click()这段代码即可直接将 html 判断下载,下载的文件名称就是 zhangsan.html
demo2
<body>
  <input type="file" id="fileInput">
  <script>
    window.onload = function () {
      fileInput.onchange = function (e) {
        console.log(e.target.files[0])
        const link = document.createElement('a')
        link.href = window.URL.createObjectURL(e.target.files[0])
        // link.setAttribute('download', '1111.html')
        link.download = '1111.html'
        link.click()
      }
    }
  </script>
</body>这个demo是 咱们去本地选中一个html文件,通过 e.target.files[0] 拿到的就是 继承自 Blob 的二进制对象(所以不需要 new Blob()), 即可再次去下载该文件
项目中的导出功能 方法封装
export function download (url, params) {
  $http({
    method: 'get',
    url: url,
    params: params,
    responseType: 'blob' //arraybuffer
  }).then(response => {
    if (!response) {
      return
    }
    let link = document.createElement('a')
    link.href = window.URL.createObjectURL(new Blob([response.data]))
    link.target = '_blank'
    let filename = response.headers['content-disposition']
    link.download = decodeURI(filename)  // 下载的文件名称
    document.body.appendChild(link)  // 添加创建的 a 标签 dom节点
    link.click()  // 下载
    document.body.removeChild(link)  // 移除节点
  }).catch(error => {})
}上面有用到decodeURI, 这里就简单扩充一下 decodeURL 和 encodeURI
encodeURI() 函数可把字符串作为 URI 进行编码
decodeURI() 函数可对 encodeURI() 函数编码过的 URI 进行解码
例子:
let a = '李四'
encodeURI(a)  //'%E6%9D%8E%E5%9B%9B'let a = encodeURI('李四') // '%E6%9D%8E%E5%9B%9B'
decodeURI(a)  // '李四'                










