【问题标题】:Dart: http post upload to google DriveDart:http post上传到google Drive
【发布时间】:2018-12-13 18:53:10
【问题描述】:

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

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"

飞镖版本:

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 drive 发送文件 http 请求吗?

【问题讨论】:

    标签: dart flutter


    【解决方案1】:

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

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

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

    【讨论】:

    • 谢谢它的工作!我已将request.fields['metadata']..request.files.add ... 替换为request.files.add
    • 一直坚持这一点。这不起作用。该名称始终为无标题。似乎元数据需要作为多部分/相关内容类型传递,但随后我得到 400
    猜你喜欢
    • 2012-11-09
    • 2020-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-11
    • 1970-01-01
    • 2018-11-11
    • 1970-01-01
    相关资源
    最近更新 更多