当前位置:网站首页>How to cache with blob object in browser
How to cache with blob object in browser
2022-07-22 08:18:00 【Code Taoist】
In the browser Blob Object is a class file object of immutable raw data ; They can be read as text or binary data or converted into ReadableStream, Therefore, its method can be used to process data .
utilize blob characteristic , We can easily convert pictures or audio and video into data in memory , This reduces network latency , Enhance user experience .
1. Get ready Blob data
Use the built-in fetch You can easily convert the response content into blob:
async function createBlob() {
const response = await fetch(
'https://miro.medium.com/max/1400/1*sAUnjuM5TXHlf7Qdef84jw.png',
);
const blob = await response.blob();
return blob;
}
Or use axios:
async function createBlob() {
const { data } = await axios(
'https://miro.medium.com/max/1400/1*sAUnjuM5TXHlf7Qdef84jw.png',
{ responseType: 'blob' },
);
return data;
}
Output in the console :
2. How to use Blob Generate URL?
We can use URL.createObjectURL() take blob Convert to URL, Then we can use this ordinary URL.
Of course , There's a price . Use URL.createObjectURL() when , Indicates that there is a pair blob References to data , If not used URL.revokeObjectURL(), Then the data will always occupy memory , Until the page refreshes or closes . This is likely to cause memory leaks . So be careful to release it at the right time .
3. How to persist Blob data ?
Use URL.createObjectURL() Can be thought of as “ Persistence ” Data in memory . But what if we want to persist it to disk ?
We can use the browser to store API, for example LocalStorage、SessionStorage、IndexedDB etc. .
Let's start with LocalStorage:
const blob = await createBlob();
// Convert blob to base64 string
const reader = new FileReader();
reader.addEventListener('load', () => {
localStorage.setItem("imageURL", reader.result);
});
// Read the contents of the specified Blob or File
reader.readAsDataURL(blob);
because LocalStorage Of keyValue It can only be a string , So we must put Blob Convert to string type . Use here FileReader.readAsDataURL() The function converts it to base64 Encoded string .
This is the complete code :
void (async () => {
const blob = await createBlob();
// Convert blob to base64 string
const reader = new FileReader();
reader.addEventListener('load', () => {
localStorage.setItem('imageURL', reader.result);
});
// Read the contents of the specified Blob or File
reader.readAsDataURL(blob);
// Take out when in use:
setTimeout(() => {
showImage();
}, 2000);
})();
async function createBlob() {
const response = await fetch(
'https://miro.medium.com/max/1400/1*sAUnjuM5TXHlf7Qdef84jw.png'
);
const data = await response.blob();
return data;
}
async function showImage() {
const imageURL = localStorage.getItem('imageURL');
console.log('imageURL: ', imageURL);
document.querySelector('img').src = imageURL;
}
Next use IndexedDB:
<img alt="" />
<script>
function promisifyRequest(request) {
return new Promise((resolve, reject) => {
request.oncomplete = request.onsuccess = () => resolve(request.result);
request.onabort = request.onerror = () => reject(request.error);
});
}
function createStore(dbName, storeName) {
const request = indexedDB.open(dbName);
request.onupgradeneeded = () => request.result.createObjectStore(storeName);
const dbp = promisifyRequest(request);
return (txMode, callback) =>
dbp.then((db) =>
callback(db.transaction(storeName, txMode).objectStore(storeName)),
);
}
let defaultGetStoreFunc;
function defaultGetStore() {
if (!defaultGetStoreFunc) {
defaultGetStoreFunc = createStore('keyval-store', 'keyval');
}
return defaultGetStoreFunc;
}
function set(key, value, customStore = defaultGetStore()) {
return customStore('readwrite', (store) => {
store.put(value, key);
return promisifyRequest(store.transaction);
});
}
function get(key, customStore = defaultGetStore()) {
return customStore('readonly', (store) => promisifyRequest(store.get(key)));
}
void (async () => {
const blob = await createBlob();
await set('imageBlob', blob);
// Take out when in use:
setTimeout(() => {
showImage();
}, 2000);
})();
async function createBlob() {
const response = await fetch(
'https://miro.medium.com/max/1400/1*sAUnjuM5TXHlf7Qdef84jw.png',
);
const data = await response.blob();
return data;
}
async function showImage() {
const blob = await get('imageBlob');
const objectURL = URL.createObjectURL(blob);
document.querySelector('img').src = objectURL;
// URL.revokeObjectURL(objectURL);
}
</script>
ad locum , I use the idb-keyval Part of IndexedDB Code . You can see that we can directly store the original blob data . This is because IndexedDB Not only can I store strings , You can also store binary data (ArrayBuffer Objects and Blob object ).
Besides , Note that these browsers store API The capacity limit of . for example localStorage about 5MB, and IndexedDB Suitable for storing large amounts of data , It is calculated according to the available disk space ,“ Group ” Limit ( For a given domain , Including all its subdomains ) Ranges can be obtained from 10MB To 2GB. More about , see also MDN.
Conclusion
Image caching can also be used Canvas API, but Blob It can be used for various media types . You have other things blob Use cases ? Feel free to share your thoughts with me .
边栏推荐
- Cmake uses the boost static library, and the error prompt is to find the could not find boost (missing: system thread filesystem
- R语言使用ggpubr包的ggarrange函数将多幅图像组合起来、使用ggexport函数将可视化图像保存为tiff格式(width参数指定宽度、height参数指定高度、res参数指定分辨率)
- mysql的binlog
- R language tests the significance of correlation coefficient: use cor.test function to calculate the value and confidence interval of correlation coefficient and its statistical significance (if the v
- vector介绍及底层原理
- No.js 的模块加载器实现
- Matrix multiplication and division of two elements "suggestions collection"
- CDH 6.1 环境搭建图文教程
- Didi received 8billion fines, and the data security sector rose sharply. Qianxin rose 5.6% in midday trading
- Detailed explanation of UNET (with graphics and code implementation)
猜你喜欢
如何设计产品MVP实现价值最大化
DS二叉树—二叉树结点的最大距离
Advanced architects, 16 common principles of microservice design and Governance
JMeter --- FTP performance test
Comment changer la police de la console en console?
Read the paper with me - multi model text recognition network
AirFlow的Scheduling的start_date解释
jmeter---ftp性能测试
Property dataSource is required 异常处理 [IDEA]
状态管理之 Zustand
随机推荐
R language uses the mean function to calculate the relative frequency of the specified variables in the sample (observation) data: calculate the proportion of the observation samples in the dataframe
一个公用的dao类和util
Mysql REGEXP不区分大小写解决办法
Web3 couldn't escape the palm of these old giants
日期处理bean
R语言的&和&&注意事项
一文教你检测MOS管好坏的五大诀窍「建议收藏」
Move! What if you can't take the PMP Exam?
Percona XtraDB Cluster安装
计算2支股票的M天运动平均价格
串应用- 计算一个串的最长的真前后缀
How to design product MVP to maximize value
Fastjson 代码执行 CVE-2022-25845
ROS manipulator movelt learning notes 1 | basic preparation
Programming in CoDeSys to realize serial communication
Detailed explanation of ternary operators in JS
[solution] the solution of requesting Excel data to return PK results under unitywebrequest
Finer grained useeffect
js中的三目运算符详解
How to make random factors in the game win the trust of players again