Blob 参考
Blob 表示不可变的原始数据,常用于生成文本文件、下载 JSON、处理图片数据、从接口响应中读取二进制内容。
语法
const blob = new Blob(parts, options);
参数
parts:数组,内容可以是字符串、ArrayBuffer、TypedArray、Blob 等。options.type:可选,表示 MIME 类型,例如text/plain;charset=utf-8。
常用属性与方法
| 属性或方法 | 说明 |
|---|---|
blob.size |
字节大小 |
blob.type |
MIME 类型 |
blob.text() |
读取为字符串 |
blob.arrayBuffer() |
读取为 ArrayBuffer |
blob.slice() |
截取一部分数据 |
示例
const content = JSON.stringify({ name: "caijiao" }, null, 2);
const blob = new Blob([content], { type: "application/json;charset=utf-8" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = "data.json";
a.click();
URL.revokeObjectURL(url);
可运行演示
源码
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Blob 下载演示</title>
<style>
* { box-sizing: border-box; }
body { margin: 0; padding: 24px; font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; color: #0f172a; background: #f8fafc; }
.demo { max-width: 720px; margin: 0 auto; padding: 20px; border: 1px solid #dbeafe; border-radius: 12px; background: #ffffff; }
textarea { width: 100%; min-height: 140px; padding: 12px; border: 1px solid #cbd5e1; border-radius: 8px; font: inherit; resize: vertical; }
button { margin-top: 14px; padding: 10px 14px; border: 0; border-radius: 8px; color: #ffffff; background: #2563eb; cursor: pointer; }
</style>
</head>
<body>
<main class="demo">
<textarea id="content">Blob 可以把浏览器中的字符串生成一个可下载文件。</textarea>
<button id="download" type="button">下载 txt 文件</button>
</main>
<script>
const textarea = document.querySelector("#content");
const button = document.querySelector("#download");
button.addEventListener("click", () => {
const blob = new Blob([textarea.value], { type: "text/plain;charset=utf-8" });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = "blob-demo.txt";
link.click();
URL.revokeObjectURL(url);
});
</script>
</body>
</html>
常见错误
- 创建对象 URL 后不释放,长时间运行的页面可能积累内存占用。
- MIME 类型写错,下载后的文件可能无法被目标程序正确识别。
- 大文件不适合全部拼进内存再创建 Blob,应考虑流式处理或服务端下载。
相关内容
相关内容
- Clipboard API 参考 Clipboard API Reference,整理 navigator.clipboard.writeText 的语法、权限限制、可运行演示、常见错误和相关问...
- FormData 参考 FormData Reference,整理表单字段读取、文件上传、append、set、entries、fetch 提交和常见错误。
- URL API 参考 URL API Reference,整理 URL 构造函数、常用属性、查询参数处理、对象 URL、示例和常见错误。
- URLSearchParams 参考 URLSearchParams Reference,整理查询参数读取、追加、修改、删除、序列化、可运行演示和常见错误。
- Web Crypto API 参考 Web Crypto API Reference,整理 crypto.randomUUID、crypto.subtle.digest、SHA 哈希、HTTPS...
- Web Storage 参考 Web Storage Reference,整理 localStorage、sessionStorage、setItem、getItem、removeItem、...