Dart: http post upload to google Drive

2019-07-31 09:17发布

问题:

I try to upload a file to google Drive in Dart after successful upload one with a command line curl command:

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"

the dart version:

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);
}

I get a status code bad request: 400

Can someone help me to send a file http request to google drive in Dart ?

回答1:

When you want to add a more complex form item to MultipartRequest, you add it as a file. (Yes, slightly strange...)

Replace request.fields.add... with...

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


标签: dart flutter