3

I am trying to upload some pictures taken in my application to Google Drive.

I created a project and a Service account key and I have Google Drive API enabled.

My code snippet looks like this:

// sfilePath = "/storage/emulated/0/Xyz";
// sfileName = "PIC_17";

final accountCredentials = new ServiceAccountCredentials.fromJson({
"private_key_id": "...",
"private_key": "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n",
"client_email": "...@...gserviceaccount.com",
"client_id": "...apps.googleusercontent.com",
"type": "service_account"

});

AuthClient client = await clientViaServiceAccount(
  accountCredentials,
  ['https://www.googleapis.com/auth/drive']);

var driveApi = ga.DriveApi(client);

var fileToUpload = File(sfilePath + sfileName + '.jpg');

var response = await driveApi.files.create(ga.File()..name = 'my_file.jpg',
     uploadMedia: ga.Media(fileToUpload.openRead(), fileToUpload.lengthSync()));

print(response.toJson());  

After running the program

print(response.toJson())

results in:

{id: ..., kind: drive#file, mimeType: image/jpeg, name: my_file.jpg} 

and I see the Requests number for Google Drive API on Dashboard increasing after a while, but I can't find my_file.jpg on my Google Drive.

What could be the problem? How could I test what happens, what is the exact response?

My solution is from: Dart: upload .jpg file to google Drive

Thanks, IMozes

IMozes
  • 121
  • 1
  • 6

2 Answers2

0

I think the problem is that you are using a Service Account. When using Service Account Key the Apis are working but your file is not stored in YOUR Google Drive but in a separated Google Drive. To check this you can add the following code

var fileList = await driveApi.files.list();
fileList.files.forEach((file) => print('---${file.name})'));

Using Service Account Key, you will have only one file named "welcome..".

The solution is to use Firebase Authentication with Google API Key with a code like:

final FirebaseAuth _auth = FirebaseAuth.instance;
final GoogleSignIn googleSignIn = GoogleSignIn(
scopes: ['https://www.googleapis.com/auth/drive'],
);

final GoogleSignInAccount googleSignInAccount = await 
googleSignIn.signIn();
final GoogleSignInAuthentication googleSignInAuthentication =
  await googleSignInAccount.authentication;


final AuthCredential credential = GoogleAuthProvider.getCredential(
accessToken: googleSignInAuthentication.accessToken,
idToken: googleSignInAuthentication.idToken,
);

AuthResult authResult = await _auth.signInWithCredential(credential);


var client = GoogleHttpClient(await googleSignInAccount.authHeaders);

var driveApi = drive.DriveApi(client);

Where GoogleHttpClient is defined like here https://stackoverflow.com/a/48485898/8676527

Zebra
  • 103
  • 1
  • 7
0

You must share your drive folder where you upload image with the client_email of credential