Last active
May 7, 2020 18:17
-
-
Save renzhezhilu/a500ed1b10de4222f5338eeb4404d77e to your computer and use it in GitHub Desktop.
[Cache_files_to_browser]#Uint8Array_to_text #text_to_Blob
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function fileSaveLocal(fileUrl = 'https://cdn.jsdelivr.net/npm/[email protected]/dist/localforage.min.js', | |
name = '未命名', | |
type = 'text/txt') { | |
let blobUrl = null | |
let isHave = localStorage.getItem(name) | |
function getData() { | |
let txtData = localStorage.getItem(name) | |
let u = new Uint8Array(JSON.parse(txtData)) | |
let b = new Blob([u.buffer], { | |
type: type | |
}) | |
blobUrl = URL.createObjectURL(b) | |
} | |
async function fetchData() { | |
await fetch(fileUrl) | |
.then(d => d.arrayBuffer()) | |
.then(d => [...new Uint8Array(d)]) | |
.then(d => { | |
localStorage.setItem(name, JSON.stringify(d)) | |
}) | |
} | |
if (isHave) { | |
getData() | |
console.log('本地已存在'); | |
} else { | |
fetchData() | |
getData() | |
console.log('请求后存储', data); | |
} | |
return blobUrl | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment