const a = doucment.createElement('a')
a.href="url"
a.download=filename
doucment.body.appendChild(a)
a.click()
doucment.body.removeChild(a)
image,video类型的数据会直接打开
- 数据转base64下载解决自动打开问题
const xhr = new XMLHttpRequest();
xhr.open('get',url,true);
xhr.responseType = "blob"; // 返回类型blob 存储着大量的二进制数据
xhr.onload=function(){
if(this.status===200){
const blob = this.response();
const reader = new FileReader(); //是一种异步文件读取机制
reader.readAsDataURL(blob); //读取文件内容,会将文件内容进行base64编码后输出
reader.onload = function(){
const a = doucment.createElement('a')
a.href = e.target.result;
a.download=filename
doucment.body.appendChild(a)
a.click()
doucment.body.removeChild(a)
}
}
}
视频转base64过大会下载失败
- 解决使用base64过大问题
const xhr = new XMLHttpRequest();
xhr.open('get',path,true);
xhr.responseType = "blob";
xhr.onload=function(){
if(this.status===200){
const blob = this.response();
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = function(){
const binStr = atob(e.target.result.split(',')[1]), //atob解码使用base64编码的字符串
len = binStr.length,
// 数组类型表示一个8位无符号整型数组,创建时内容被初始化为0。创建完后,可以以对象的方式或使用数组下标索引的方式引用数组中的元素
arr = new Uint8Array(len);
for (let i = 0; i < len; i++) {
arr[i] = binStr.charCodeAt(i);
}
const a = document.createElement('a');
a.download = filename;
const url = URL.createObjectURL(new Blob([arr])); //获取当前文件的一个内存URL
a.href = url
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(url); //释放 blob
}
}
}