Skip to content

Instantly share code, notes, and snippets.

@renzhezhilu
Last active May 7, 2020 18:17
Show Gist options
  • Save renzhezhilu/a500ed1b10de4222f5338eeb4404d77e to your computer and use it in GitHub Desktop.
Save renzhezhilu/a500ed1b10de4222f5338eeb4404d77e to your computer and use it in GitHub Desktop.
[Cache_files_to_browser]#Uint8Array_to_text #text_to_Blob
function fileSaveLocal(fileUrl = 'https://cdn.jsdelivr.net/npm/localforage@1.7.3/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