当前位置:   article > 正文

使用Blob实现文件下载_blob链接怎么下载

blob链接怎么下载

大家都知道 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

  1. let html = `
  2. <div>
  3. <div>
  4. <p style="color: red;font-size: 20px;">张三</p>
  5. </div>
  6. </div>
  7. `
  8. const link = document.createElement('a')
  9. link.setAttribute('download', 'zhangsan.html')
  10. // link.download = 'zhangsan.html'
  11. link.href = window.URL.createObjectURL(new Blob([html], { type: 'text/html' }))
  12. link.click()

这段代码即可直接将 html 判断下载,下载的文件名称就是 zhangsan.html 

demo2 

  1. <body>
  2. <input type="file" id="fileInput">
  3. <script>
  4. window.onload = function () {
  5. fileInput.onchange = function (e) {
  6. console.log(e.target.files[0])
  7. const link = document.createElement('a')
  8. link.href = window.URL.createObjectURL(e.target.files[0])
  9. // link.setAttribute('download', '1111.html')
  10. link.download = '1111.html'
  11. link.click()
  12. }
  13. }
  14. </script>
  15. </body>

这个demo是 咱们去本地选中一个html文件,通过 e.target.files[0] 拿到的就是 继承自 Blob 的二进制对象(所以不需要 new Blob()), 即可再次去下载该文件 

 项目中的导出功能 方法封装

  1. export function download (url, params) {
  2. $http({
  3. method: 'get',
  4. url: url,
  5. params: params,
  6. responseType: 'blob' //arraybuffer
  7. }).then(response => {
  8. if (!response) {
  9. return
  10. }
  11. let link = document.createElement('a')
  12. link.href = window.URL.createObjectURL(new Blob([response.data]))
  13. link.target = '_blank'
  14. let filename = response.headers['content-disposition']
  15. link.download = decodeURI(filename) // 下载的文件名称
  16. document.body.appendChild(link) // 添加创建的 a 标签 dom节点
  17. link.click() // 下载
  18. document.body.removeChild(link) // 移除节点
  19. }).catch(error => {})
  20. }

 上面有用到decodeURI, 这里就简单扩充一下 decodeURL 和 encodeURI

encodeURI() 函数可把字符串作为 URI 进行编码

decodeURI() 函数可对 encodeURI() 函数编码过的 URI 进行解码

例子: 

  1. let a = '李四'
  2. encodeURI(a) //'%E6%9D%8E%E5%9B%9B'
  1. let a = encodeURI('李四') // '%E6%9D%8E%E5%9B%9B'
  2. decodeURI(a) // '李四'
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/145201
推荐阅读
相关标签
  

闽ICP备14008679号