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

Dart上传JPG至Google Drive报400错误,求问题排查

解决Dart上传文件到Google Drive返回400 Bad Request的问题

我帮你梳理下代码里的几个关键问题,这些正是导致400错误的核心原因:

主要问题点:

  • 重复定义metadata:你同时在request.fields和request.files里配置了metadata,这会让请求结构混乱,Google Drive API无法正确解析。
  • 缺少实际文件内容part:你的代码只上传了metadata,完全没添加要上传的.jpg文件本身,这是最关键的错误。
  • metadata格式错误:手动拼接的JSON字符串不规范(比如name没有用双引号包裹),而且request.fields里的写法不符合multipart上传的要求。
  • 文件名包含本地路径:Google Drive的name字段只需要文件名(比如test.jpg),不需要带上本地存储路径,这虽然不是直接导致400的原因,但会让Drive里的文件名变得不合理。

修正后的代码:

import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;

// ... 你的其他业务代码 ...

final access_token = '...'; 
// sfilePath is "/storage/emulated/0/test/" 
// sfileName is "test" 
final fileName = '$sfileName.jpg';
final localFile = File('$sfilePath$fileName');

// 先检查文件是否存在,避免后续无效请求
if (!await localFile.exists()) {
  print('目标文件不存在,请检查路径是否正确');
  return;
}

Uri uri = Uri.parse('https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart'); 
http.MultipartRequest request = http.MultipartRequest('POST', uri); 
request.headers["Authorization"] = "Bearer $access_token"; 

// 1. 添加metadata部分:用标准JSON格式生成,仅传递文件名
request.files.add(http.MultipartFile.fromString(
  'metadata',
  jsonEncode({'name': fileName}),
  contentType: http.MediaType('application', 'json'),
));

// 2. 添加实际的jpg文件内容,指定正确的媒体类型
request.files.add(await http.MultipartFile.fromPath(
  'file',
  localFile.path,
  contentType: http.MediaType('image', 'jpeg'),
));

http.StreamedResponse response = await request.send(); 
print('响应状态码:${response.statusCode}');

// 可选:获取API返回的错误详情,帮助快速排查问题
if (response.statusCode != 200) {
  final errorDetails = await response.stream.bytesToString();
  print('错误详情:$errorDetails');
}

额外注意事项:

  1. 权限验证:确保你的access_token拥有https://www.googleapis.com/auth/drive.file或更高的Drive上传权限,权限不足也会返回400或403错误。
  2. 文件读取权限:确认你的App有读取本地存储的权限(比如Android的READ_EXTERNAL_STORAGE),否则无法读取目标文件内容。
  3. 错误详情排查:上面代码里添加了获取错误详情的逻辑,Google Drive API通常会返回具体的错误描述,能帮你快速定位剩余问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:50:01