← 中文资源

简体中文版本

Object URL 的创建与撤销生命周期

createObjectURL 把 Blob 绑定到 blob: URL,revokeObjectURL 解绑释放;同一 Blob 多次创建得到不同 URL,重复 revoke 是安全的 no-op,预览与下载链接要成对调用。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

scheme: blob
blob size: 30 bytes
urls are distinct: true
both urls revoked, double revoke is safe

实现说明

顶层就这几处状态:blob、url、second。

使用要点

  • 演示输出是带标签的(scheme:、blob size:、urls are distinct:),每个操作都会留下自己的一行标注。

常见问题

复制和运行之间有安装步骤吗?

没有。从复制到运行之间没有别的要做。 状态都挂在模块顶层:blob、url、second。

核心语句

const blob = new Blob(['report,line,amount\n1,coffee,350'], { type: 'text/csv' });
const second = URL.createObjectURL(blob);
const url = URL.createObjectURL(blob);

代码示例

// createObjectURL binds a Blob to a blob: URL; revokeObjectURL unbinds and frees it -
// they must come in pairs, otherwise the reference pins the underlying resource
const blob = new Blob(['report,line,amount\n1,coffee,350'], { type: 'text/csv' });
const url = URL.createObjectURL(blob);

console.log('scheme:', url.split(':')[0]);
console.log('blob size:', blob.size, 'bytes');

// Calling createObjectURL on the same Blob again produces a fresh URL
const second = URL.createObjectURL(blob);
console.log('urls are distinct:', url !== second);

// After revocation the URL is dead - no navigation, download, or preview through it
URL.revokeObjectURL(url);
URL.revokeObjectURL(second);

// Revoking twice is a safe no-op: cleanup logic can call it liberally
URL.revokeObjectURL(url);
console.log('both urls revoked, double revoke is safe');