NestJS API返回Blob图片异常:Insomnia空响应、前端数据丢失
NestJS API 返回 Blob 图片数据异常排查与解决
问题核心
NestJS接口中控制台打印Blob数据正常,但通过Insomnia调用返回空对象,前端尝试重新转换为Blob后数据丢失(原大小50k+变为15字节),本质是NestJS默认的响应序列化机制无法正确处理Blob对象,会将其序列化为空JSON对象。
解决方法
方法1:使用StreamableFile(官方推荐)
NestJS提供专门的StreamableFile类处理文件/Blob响应,自动适配响应头和数据格式:
- 导入依赖
import { StreamableFile } from '@nestjs/common'; import { Readable } from 'stream';
- 接口逻辑实现
- 若处理本地文件:
@Get('image') @Header('Content-Type', 'image/png') getLocalImage(): StreamableFile { const fileStream = createReadStream(join(process.cwd(), 'assets/your-image.png')); return new StreamableFile(fileStream); }
- 若处理内存中的Blob:
@Get('image') @Header('Content-Type', 'image/png') async getMemoryBlob(): Promise<StreamableFile> { const blob = await yourBlobGenerationFunction(); // 获取目标Blob const buffer = await blob.arrayBuffer(); // 将Buffer转为可读流 const stream = new Readable(); stream.push(Buffer.from(buffer)); stream.push(null); // 标记流结束 return new StreamableFile(stream); }
方法2:手动构造响应对象
直接通过Express的Response对象手动写入数据并设置响应头:
import { Response } from 'express'; @Get('image') async sendBlob(@Res() res: Response) { const blob = await yourBlobGenerationFunction(); const buffer = await blob.arrayBuffer(); // 设置正确的响应头 res.setHeader('Content-Type', blob.type); res.setHeader('Content-Length', buffer.byteLength); // 发送Buffer数据 res.send(Buffer.from(buffer)); }
异常原因说明
当直接返回Blob对象时,NestJS会用JSON序列化器处理,但Blob属于浏览器/Node环境的特殊对象,可枚举属性极少,序列化后就变成了空对象{}。这就是Insomnia显示空对象、前端转Blob后数据仅15字节的原因——实际返回的是空JSON字符串,而非真正的Blob二进制数据。
内容的提问来源于stack exchange,提问作者Murilo AA Alves
相关产品推荐
相关产品推荐

