2

I try to upload a .jpg file to google Drive in Dart:

final access_token = '...';

// sfilePath is "/storage/emulated/0/test/"
// sfileName is "test"

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 : " + sfileName + '.jpg' +  "};type=application/json;charset=UTF-8";
request.files.add(http.MultipartFile.fromString('metadata',
                                  JSON.jsonEncode({'name': sfilePath + sfileName + '.jpg'}),
                                  contentType: MediaType('application', 'json'),
                  ));

http.StreamedResponse response = await request.send();
print('>>>>>>>>>>>>>>>>>>>>>' + response.statusCode.toString());

I get a status code bad request: 400 I saw the post about the same isue: Dart: http post upload to google Drive

What am I missing? Thanks

IMozes
  • 121
  • 1
  • 6

1 Answers1

3

Maybe you could use the googleapis package. It could be simpler to use.

Add this dependencies in your pubspec.yaml

dependencies:
  googleapis:
  googleapis_auth:

And use the googleapis library:

import 'package:googleapis/drive/v3.dart';
import 'package:googleapis_auth/auth_io.dart';
import 'dart:io' as io;

main() async {
  AuthClient client = await clientViaServiceAccount(
      ServiceAccountCredentials.fromJson({/* here the credentials */}),
      ['https://www.googleapis.com/auth/drive']);

  var driveApi = DriveApi(client);

  var fileToUpload = io.File('my_file.png');

  await driveApi.files.create(File()..name = 'my_file.png',
      uploadMedia: Media(fileToUpload.openRead(), fileToUpload.lengthSync()));
}
Xavier
  • 3,647
  • 24
  • 17
  • most of the upload code ive come across look like this. is there a way to actually get the progress of the upload? – chitgoks Dec 29 '19 at 02:21
  • @Xavier Is there a way to upload to a specific folder? like to specify the folder name, if it exist then upload the file to it if not create it and upload the file to it – ler Jun 18 '20 at 20:55