1.实现原理
生成blob对象,再使用URL.createObjectURL() 创建一个非跨域的数据源,然后在页面写入a标签支持下载。
Blob表示二进制类型的大对象,通常是影像、声音或多媒体文件0。
通过URL.createObjectURL(blobVal) 获取要保存的文件的一个URL,这个URL带hash,保存在内存中。
通过URL.revokeObjectURL()来释放这个object URL,通知浏览器不再继续引用这个文件
跨域文件下载处理方法:
download 就是跨域的问题,如果加载了非同源的内容,该属性会失效不能下载,只会在浏览器中导航到该内容。
在服务器设置 Content-Disposition 使用HTTP响应头 Content-Disposition 进行处理。
先下载源数据文件,生成blob对象,再使用URL.createObjectURL()创建一个非跨域的数据源,然后在页面写入a标签支持下载。
2.代码实现
<template>
<div>URL.createObjectURL、Blob 实现保存文件</div>
<button ref="btnRef">下载</button>
</template>
<script setup lang='ts'>
import {onMounted, ref} from 'vue'
let btnRef = ref()
let fileUrl = ''
onMounted(()=>{
btnRef.value.addEventListener('click',()=>{
let str = '这里时要保存的文字内容'
const blobVal = new Blob([str],{type:'text/plain'})
console.log(blobVal);
// 创建了一个blob 的地址
fileUrl = URL.createObjectURL(blobVal)
console.log(fileUrl);
let aDom = document.createElement('a')
// 第一种写法
// aDom.setAttribute('href',fileUrl)
// aDom.setAttribute('download','导出文件.txt')
// 第二种写法
aDom.href = fileUrl
aDom.download = '导出文件.txt'
aDom.click()
URL.revokeObjectURL(fileUrl)
})
})
</script>
<style scoped lang='less'>
</style>
3.结果显示
