@longmo-utils/browser / blobToObjectURL
Function: blobToObjectURL()
ts
function blobToObjectURL(blob): string;将 Blob 转换为 Object URL
生成的 URL 必须手动调用 URL.revokeObjectURL() 释放,否则会造成内存泄漏
Parameters
| Parameter | Type | Description |
|---|---|---|
blob | Blob | 要转换的 Blob 对象 |
Returns
string
返回 Object URL(blob: 开头的 URL)
Examples
typescript
const blob = new Blob(['hello world'], { type: 'text/plain' });
const url = blobToObjectURL(blob);
console.log(url); // 'blob:https://example.com/uuid'
// 使用完后记得释放
URL.revokeObjectURL(url);typescript
const blob = await fetch('image.png').then(r => r.blob());
const url = blobToObjectURL(blob);
const img = document.createElement('img');
img.src = url;
document.body.appendChild(img);
// 图片加载后或组件卸载时释放
URL.revokeObjectURL(url);typescript
const blob = new Blob(['file content'], { type: 'text/plain' });
const url = blobToObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'file.txt';
a.click();
// 点击后释放
URL.revokeObjectURL(url);typescript
useEffect(() => {
const blob = createBlob();
const url = blobToObjectURL(blob);
setSrc(url);
return () => {
URL.revokeObjectURL(url); // 清理函数中释放
};
}, []);