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'); }
额外注意事项:
- 权限验证:确保你的
access_token拥有https://www.googleapis.com/auth/drive.file或更高的Drive上传权限,权限不足也会返回400或403错误。 - 文件读取权限:确认你的App有读取本地存储的权限(比如Android的
READ_EXTERNAL_STORAGE),否则无法读取目标文件内容。 - 错误详情排查:上面代码里添加了获取错误详情的逻辑,Google Drive API通常会返回具体的错误描述,能帮你快速定位剩余问题。
内容的提问来源于stack exchange,提问作者IMozes
相关产品推荐
相关产品推荐

