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

Flutter中尝试Google Drive部分下载触发Header错误

Flutter中使用Google Drive API部分下载音频文件时出现Content-Range头为空错误

问题分析

你的代码核心问题在于调用files.get时没有指定获取媒体内容。默认情况下,files.get请求的是文件的元数据(JSON格式),而非实际的文件内容,因此服务器不会返回Content-Range头,导致SDK抛出"Attempting partial download but got invalid 'Content-Range' header"错误。

你的认证、文件列表/元数据获取正常,说明权限和API调用基础逻辑没问题,只是部分下载的请求参数缺失关键配置。

解决方案

在调用files.get时添加alt: 'media'参数,明确要求获取文件的媒体内容,同时保留PartialDownloadOptions指定字节范围:

import 'package:googleapis/drive/v3.dart' as ga;    
(...)
try {
  var partiallyDownloadedFile = await api.files.get(
    "myFileIdHere",
    alt: 'media', // 必须:指定获取文件媒体内容
    downloadOptions: ga.PartialDownloadOptions(ga.ByteRange(0, 10))
  ); 
  print("partial download succeeded");
  print(partiallyDownloadedFile);
  
  // 读取部分下载的字节数据
  List<int> audioHeaderBytes = [];
  await for (var chunk in partiallyDownloadedFile.stream) {
    audioHeaderBytes.addAll(chunk);
  }
  // 在这里处理音频元数据解析(比如解析WAV/MP4的头信息)
  return;
} catch (err) {
  print('Error occured : ');
  print(err);
  return;
}

额外注意事项

  • 确保目标文件是非Google原生格式(你测试的WAV/MP4符合要求),Google文档/表格等原生格式无法直接通过alt:media下载原始内容。
  • 检查文件大小是否大于你指定的字节范围(比如0-10需要文件至少11字节),如果文件过小,服务器会返回200状态码而非206,但SDK会自动处理完整内容。
  • 如果上述方案仍有问题,可以绕开SDK的PartialDownloadOptions,直接使用已认证的HTTP客户端手动发送带Range头的请求:
// 先获取文件的下载链接
var fileMeta = await api.files.get("myFileIdHere", $fields: "webContentLink");
var downloadUrl = fileMeta.webContentLink;

// 使用GoogleSignIn的认证客户端发送请求
var httpClient = await _googleSignIn.authenticatedClient();
var response = await httpClient.get(
  Uri.parse(downloadUrl),
  headers: {'Range': 'bytes=0-10'}
);

if (response.statusCode == 206) {
  List<int> bytes = response.bodyBytes;
  // 处理字节数据
} else {
  print('部分下载失败:${response.statusCode}');
}

内容的提问来源于stack exchange,提问作者Restless Innocence

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 09:45:34