Dart:http post 上传到 google Drive

标签 dart flutter

使用命令行curl命令成功上传文件后,我尝试在Dart中将文件上传到google云端硬盘:

curl -X POST -L \
    -H "Authorization: Bearer $access_token" \
    -F "metadata={name : 'test_send_file.zip'};type=application/json;charset=UTF-8" \
    -F "file=@test_send_file.zip;type=application/zip" \
    "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart"

Dart 版本:

import 'package:http/http.dart' as http;
import 'package:http_parser/http_parser.dart';

final access_token = "....";

main() async {
  File first = File('test_send_file.zip');
  Uri uri = Uri.parse(
      'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart');

  http.MultipartRequest request = new http.MultipartRequest('POST', uri);

  request.headers["Authorization"] = "Bearer $access_token";
  request.fields['metadata'] =
      "{name : test_send_file.zip};type=application/json;charset=UTF-8";
  request.files.add(await http.MultipartFile.fromPath('test_send_file.zip', first.path,
      contentType: new MediaType('application', 'zip')));
  print("request.toString: " + request.toString());
  http.StreamedResponse response = await request.send();
  print(response.statusCode);
}

我收到错误请求状态代码:400

有人可以帮我在 Dart 中向 google 驱动器发送文件 http 请求吗?

最佳答案

当您想要向 MultipartRequest 添加更复杂的表单项时,可以将其添加为文件。 (是的,有点奇怪......)

request.fields.add... 替换为...

  request.files.add(http.MultipartFile.fromString(
    'metadata',
    json.encode({'name': 'test_send_file.zip'}),
    contentType: MediaType('application', 'json'),
  ));

关于Dart:http post 上传到 google Drive,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53768362/

相关文章:

如果已经被拒绝,Flutter Permission Handler 不会重新请求许可

visual-studio - flutter 命令不会从终端执行,需要很长时间

flutter - 如何在 flutter 中禁用整个设备(测试设备-android 和 iOS)的 firebase 分析?

firebase - Flutter:Firebase 如何更改查询和内容

flutter - 检查SQFLITE数据库中是否存在PK列表中的哪些PK

dart - 在 Dart 中动态设置变量名

dart - 添加或删除项目时 SliverList 不会更新

flutter - 将 List<String> 转换为 List<Map<String,dynamic>>

dart - 如何修复 future<int> 类型的值不能分配给 int 类型的变量

flutter - GetxControllers 是否会自动关闭 obs 流?