前端 Blob 详解
1. 什么是 Blob?
Blob(Binary Large Object)表示二进制大对象,用于存储二进制数据。在前端开发中,Blob 常用于处理文件、图像、视频等二进制数据。
2. 创建 Blob
可以通过 Blob
构造函数创建 Blob 对象。
const blob = new Blob(array, options);
- array: 数组,包含要放入 Blob 的数据。可以是字符串、ArrayBuffer、ArrayBufferView、Blob 等。
- options: 可选参数,包含两个属性:
type
: 指定 Blob 的 MIME 类型,如'text/plain'
、'image/png'
等。endings
: 指定行结束符的处理方式,默认为'transparent'
。
示例:
const text = ["Hello, world!"];
const blob = new Blob(text, { type: "text/plain" });
3. Blob 的属性和方法
- 属性:
size
: Blob 对象的大小(字节)。type
: Blob 对象的 MIME 类型。
示例:
console.log(blob.size); // 13
console.log(blob.type); // 'text/plain'
- 方法:
slice(start, end, contentType)
: 返回一个新的 Blob 对象,包含原 Blob 的指定字节范围。start
: 起始字节(包含)。end
: 结束字节(不包含)。contentType
: 新 Blob 的 MIME 类型。
示例:
const slicedBlob = blob.slice(0, 5, "text/plain");
4. 使用 Blob
- 下载文件:
可以通过创建 Blob URL 实现文件下载。
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = "hello.txt";
link.click();
URL.revokeObjectURL(link.href); // 释放内存
- 读取 Blob 数据:
使用FileReader
读取 Blob 数据。
const reader = new FileReader();
reader.onload = function (event) {
console.log(event.target.result); // 读取的数据
};
reader.readAsText(blob); // 以文本形式读取
- 上传文件:
通过FormData
上传 Blob 数据。
const formData = new FormData();
formData.append("file", blob, "hello.txt");
fetch("/upload", {
method: "POST",
body: formData,
});
5. Blob 与 File
File
对象继承自 Blob
,通常用于表示用户选择的文件。File
对象包含额外的属性如 name
、lastModified
等。
示例:
const file = new File(["Hello, world!"], "hello.txt", { type: "text/plain" });
console.log(file.name); // 'hello.txt'
6. 总结
Blob 是前端处理二进制数据的重要工具,广泛应用于文件操作、数据存储和网络传输等场景。通过 Blob
构造函数、FileReader
和 FormData
等 API,可以高效地操作和传输二进制数据。