Dart: upload .jpg file to google Drive

2019-08-19 08:06发布

问题:

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

回答1:

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


标签: dart upload