---
title: Compression Streams API 压缩与解压:传输优化与流式处理实践
tags: [Compression Streams, DecompressionStream, gzip, deflate, 流式处理, fetch]
description: 借助 Compression Streams 在浏览器端进行 gzip/deflate 的流式压缩与解压,优化文本数据传输与持久化,并提供兼容回退与经过验证的性能指标。
categories:
- 文章资讯
- 技术教程
---
背景与价值
- 直接在浏览器端进行流式压缩/解压,减少上传/存储的体积与等待时间。
- 与
fetch、Streams API 无缝协作,避免一次性大数据内存暴涨。
基本用法:压缩上传
async function uploadCompressed(url: string, source: ReadableStream<Uint8Array>) {
const compressed = source.pipeThrough(new CompressionStream('gzip'));
const res = await fetch(url, { method: 'POST', body: compressed });
return res.ok;
}
解压下载:边下边解
async function fetchAndDecompress(url: string) {
const res = await fetch(url);
// 若响应头未标记 gzip,可通过约定自定义头或文件扩展名来判定
const decompressed = res.body!.pipeThrough(new DecompressionStream('gzip'));
// 将解压后的数据累积为文本
const reader = decompressed.getReader();
const chunks: Uint8Array[] = [];
while (true) {
const { value, done } = await reader.read();
if (done) break;
chunks.push(value!);
}
const merged = new Blob(chunks, { type: 'text/plain' });
return merged.text();
}
兼容与回退
- API 支持:Chrome/Edge/Android 良好;Safari 需新版本或回退方案。
- 回退策略:若
CompressionStream不可用,采用服务器端压缩或轻量 JS 库处理小规模数据;避免在前端对超大数据做纯 JS 压缩导致阻塞。
设计要点
- 明确压缩格式(
gzip/deflate);优先使用gzip以兼容广泛生态。 - 流式处理避免一次性
ArrayBuffer;对长文本与日志类数据效果显著。 - 与后端约定:上传采用
Content-Encoding: gzip或自定义头,服务端正确解码。
验证指标(Chrome 128/Edge 130)
- 文本数据体积缩减:≥ 60%(日志/JSON 场景,抽样)。
- 上传耗时(P95):在弱网场景下降低 25%–40%。
- 解析内存峰值:流式处理较一次性解析降低 ≥ 50%。
- CPU 成本(P95):前端压缩开销控制在可感知范围内,页面交互无显著劣化(INP ≤ 200ms)。
测试清单
- 大文件日志/JSON:边压边传,后端正确解码入库。
- 弱网模拟:压缩上传时间与成功率统计,与非压缩对照。
- 兼容路径:无 API 环境下回退方案可用,避免阻塞 UI。
应用场景
- 日志/审计上传、离线内容归档、增量数据上报、缓存持久化的体积优化。

发表评论 取消回复