js 使用a标签 下载资源

文档

		let data = new Blob(['hello ajanuw'], {
			type: 'application/text'
		})
		let src = window.URL.createObjectURL(data)
		let dl = document.createElement('a')
		dl.href = src;
		dl.download = 'hello.txt'
		dl.click()

切片下载

let data = new Blob(['hello ajanuw'], {
	type: 'application/text'
})
let size = data.size;
let data1 = data.slice(0, size / 2, data.type)
let data2 = data.slice(size / 2, size, data.type)
let src1 = window.URL.createObjectURL(data1)
let src2 = window.URL.createObjectURL(data2)

let dl = document.createElement('a')
dl.href = src1;
dl.download = `hello(1).txt`
dl.click() // URL.revokeObjectURL(data1)

dl.href = src2;
dl.download = `hello(2).txt`
dl.click()

下载base64 data

const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = (e) => {
    const base64Data = e.target.result as string;
    console.log(base64Data);
    const a = document.createElement('a');
    a.href = base64Data;
    a.download = 'x.txt';
    a.click();
}
posted @ 2018-07-01 18:00  Ajanuw  阅读(4284)  评论(0编辑  收藏  举报