You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在NestJS中通过Google Drive API下载图片失败问题求助

NestJS中Google Drive API下载图片仅2字节的解决方法

核心问题定位

2字节的无效文件通常是因为没有正确请求Google Drive的文件内容,而是拿到了文件元数据或错误响应(比如空JSON {})。

修复步骤

1. 确保服务层正确调用Google Drive API

调用files.get时必须添加alt: 'media'参数,同时设置响应类型为流,避免直接获取文本:

// 服务层示例代码
async downloadFile(fileId: string) {
  // 注意添加alt: 'media',并设置responseType为stream
  const response = await this.drive.files.get(
    { fileId, alt: 'media' },
    { responseType: 'stream' }
  );
  return response.data;
}

如果之前没加alt: 'media',API只会返回文件的元数据(比如文件名、ID等),而非真实文件内容。

2. 控制器正确返回文件流

需要在控制器中设置正确的响应头,并将流pipe到响应对象中,确保浏览器能识别文件类型:

// 控制器示例代码
import { Response } from 'express';
import { Get, Param, Res } from '@nestjs/common';

@Get('download/:fileId')
async downloadFile(@Param('fileId') fileId: string, @Res() res: Response) {
  const fileStream = await this.googleDriveService.downloadFile(fileId);
  
  // 可选:先获取文件元数据,设置正确的文件名和MIME类型
  const fileMeta = await this.drive.files.get({ fileId });
  const mimeType = fileMeta.data.mimeType;
  const fileName = fileMeta.data.name;

  res.setHeader('Content-Type', mimeType);
  res.setHeader('Content-Disposition', `attachment; filename="${fileName}"`);
  
  // 将文件流pipe到响应
  fileStream.pipe(res);
}

3. 排查权限与响应内容

  • 确认目标文件对服务账号有读取权限:如果文件是私有文件,需要给服务账号共享该文件,或者使用正确的授权凭证
  • 临时打印响应内容:如果还是拿到2字节内容,可以先将响应转为字符串查看,比如:
    const response = await this.drive.files.get({ fileId });
    console.log(response.data); // 查看是否是错误信息或元数据
    

内容的提问来源于stack exchange,提问作者Real George

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 16:45:02