Blob & File
下载图片缓存本地
const arrUrl = [
'https://cdn.wwads.cn/creatives/COi3HnBnyFF545MHJE1dI9uO9r1Ja4D4p0fvTPYE.png',
'https://img-blog.csdnimg.cn/20201209112911490.png'
]
//缓存取出
const srcObj = JSON.parse(window.localStorage.getItem('src') || '{}')
const keys = Object.keys(srcObj)
const base64Arr = []
// 判断缓存和链接是否有不同
const diff = arrUrl.filter(item=> {
if(keys.includes(item)){
base64Arr.push(srcObj[item])
}
return !keys.includes(item)
})
// 缓存新的链接
diff.forEach(item=>{
fetch(item, {mode: 'cors'})
.then(response => response.blob())
.then(blob => {
const file = new File([blob], 'xxxx.png');
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
const objTemp = JSON.parse(window.localStorage.getItem('src') || '{}')
window.localStorage.setItem('src', JSON.stringify({...objTemp, [item]:reader.result}))
base64Arr.push(reader.result)
};
});
})
base64Arr.forEach(item=>{
const img = document.createElement('img')
img.src = item
document.body.append(img)
})
base64转blob
export const dataURLtoBlob = (dataurl: string) => {
const arr: any[] = dataurl.split(',');
const mime = arr[0].match(/:(.*?);/)[1];
const bstr = atob(arr[1]);
let n = bstr.length;
const u8arr = new Uint8Array(n);
// eslint-disable-next-line no-plusplus
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
};
base64转file
export const dataURLtoFile = (dataurl: string, filename: string) => {
const arr: any[] = dataurl.split(',');
const mime = arr[0].match(/:(.*?);/)[1];
const bstr = atob(arr[1]);
let n = bstr.length;
const u8arr = new Uint8Array(n);
// eslint-disable-next-line no-plusplus
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, { type: mime });
};
生成文件下载
let obj = {
a: 1,
b: 2
}
let blob = new Blob([JSON.stringify(obj)], {
type: "json/plain;charset=utf-8"
});
const objUrl = URL.createObjectURL(blob);
const link = document.createElement('a');
link.download = 'data.json';
link.href = objUrl;
link.click();
URL.revokeObjectURL(objUrl);
手机Safari下载pdf,防止在线预览
let blob = 'pdf文件流'
const file = new File([blob], '名字');
const objUrl = URL.createObjectURL(file);
const link = document.createElement('a');
link.download = 'xxxxx.pdf';
link.href = objUrl;
link.click();
URL.revokeObjectURL(objUrl);
复制到剪切板
export const copyWord = (word: string) => {
const div = document.createElement('div');
document.body.appendChild(div)
div.innerText = word
try {
let selection: any = window.getSelection()
let range = document.createRange()
range.selectNode(div)
selection.removeAllRanges()
selection.addRange(range)
document.execCommand('copy')
selection.removeAllRanges()
message.success('复制成功')
} catch (e) { console.log('你的浏览器不支持复制', e) }
document.body.removeChild(div);
}