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 "[email protected]_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 ?


Solution 1: Richard Heap

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'),
  ));