知识点
- URL.createObjectURL 生成非跨域的数据源,然后在页面写入a 标签支持下载
- Blob 表示二进制类型的大对象,一般是影像,声音,多媒体等
- 通过 URL.createObjectURL(bloburl )获取要保存的文件的一个url,这个url带hash,保存在内存中
- URL.revokeObjectURL()来释放这个 object 的url ,通知浏览器可以不必继续引用这个文件
代码
vue的ref 用来操作dom 元素
<script setup>
let fileUrl = ''
const fn = (() =>{
let str = '这是一段测试文字'
const blobval = new Blob([str], {type:'text/plain'})
console.log(blobval)
fileUrl = URL.createObjectURL(blobval)
// 下载
let adom = document.createElement('a')
adom.setAttribute('href',fileUrl)
// adom.setAttribute('download','') // 不写文件的名字,默认是内存hash 的地址
adom.setAttribute('download','文件重命名.txt')
adom.click()
URL.revokeObjectURL(fileUrl)
})
</script>
<template>
<div>URL.createObjectURL,bolb 实现保存文件</div>
<button @click="fn">下载按钮</button>
</template>