Blob
Baseline 广泛可用 *
注意:此功能在 Web Workers 中可用。
Blob 接口表示一个 blob,它是一个类似文件的、不可变的原始数据对象;它可以被读取为文本或二进制数据,或者转换为 ReadableStream,以便使用其方法来处理数据。
Blob 可以表示不一定是 JavaScript 原生格式的数据。 File 接口基于 Blob,继承了 blob 的功能并扩展了对用户系统上文件的支持。
使用 Blob
要从其他非 blob 对象和数据构造 Blob,请使用 Blob() 构造函数。要创建包含另一个 blob 数据子集的 blob,请使用 slice() 方法。要获取用户文件系统上文件的 Blob 对象,请参阅 File 文档。
接受 Blob 对象的 API 也列在 File 文档中。
构造函数
Blob()-
返回一个新创建的
Blob对象,该对象包含传递到构造函数中的数组中所有数据的串联。
实例属性
实例方法
Blob.arrayBuffer()-
返回一个 Promise,该 Promise 解析为一个
ArrayBuffer,其中包含Blob的全部内容作为二进制数据。 Blob.bytes()-
返回一个 Promise,该 Promise 解析为一个
Uint8Array,其中包含Blob的内容。 Blob.slice()-
返回一个新的
Blob对象,其中包含在调用它的 blob 中指定字节范围的数据。 Blob.stream()-
返回一个
ReadableStream,可用于读取Blob的内容。 Blob.text()-
返回一个 Promise,该 Promise 解析为一个字符串,其中包含
Blob的全部内容,并将其解释为 UTF-8 文本。
示例
创建 Blob
Blob() 构造函数可以从其他对象创建 blob。例如,要从 JSON 字符串构造一个 blob
const obj = { hello: "world" };
const blob = new Blob([JSON.stringify(obj, null, 2)], {
type: "application/json",
});
创建表示类型化数组内容的 URL
以下示例创建了一个 JavaScript 类型化数组,并创建一个包含该类型化数组数据的新 Blob。然后调用 URL.createObjectURL() 将 blob 转换为 URL。
<p>
This example creates a typed array containing the ASCII codes for the space
character through the letter Z, then converts it to an object URL. A link to
open that object URL is created. Click the link to see the decoded object URL.
</p>
出于示例目的,此代码中的主要部分是 typedArrayToURL() 函数,该函数从给定的类型化数组创建 Blob 并返回其对象 URL。在将数据转换为对象 URL 后,它可用于多种方式,包括作为 <img> 元素的 src 属性的值(当然,前提是数据包含图像)。
function showViewLiveResultButton() {
if (window.self !== window.top) {
// Ensure that if our document is in a frame, we get the user
// to first open it in its own tab or window. Otherwise, this
// example won't work.
const p = document.querySelector("p");
p.textContent = "";
const button = document.createElement("button");
button.textContent = "View live result of the example code above";
p.append(button);
button.addEventListener("click", () => window.open(location.href));
return true;
}
return false;
}
if (!showViewLiveResultButton()) {
function typedArrayToURL(typedArray, mimeType) {
return URL.createObjectURL(
new Blob([typedArray.buffer], { type: mimeType }),
);
}
const bytes = new Uint8Array(59);
for (let i = 0; i < 59; i++) {
bytes[i] = 32 + i;
}
const url = typedArrayToURL(bytes, "text/plain");
const link = document.createElement("a");
link.href = url;
link.innerText = "Open the array URL";
document.body.appendChild(link);
}
从 Blob 中提取数据
读取 Blob 内容的一种方法是使用 FileReader。以下代码将 Blob 的内容读取为类型化数组
const reader = new FileReader();
reader.addEventListener("loadend", () => {
// reader.result contains the contents of blob as a typed array
});
reader.readAsArrayBuffer(blob);
读取 Blob 内容的另一种方法是使用 Response。以下代码将 Blob 的内容读取为文本
const text = await new Response(blob).text();
或者使用 Blob.text()
const text = await blob.text();
通过使用 FileReader 的其他方法,可以将 Blob 的内容读取为字符串或数据 URL。
规范
| 规范 |
|---|
| File API # blob-section |
浏览器兼容性
加载中…