upload image files using google drive Api

2019-08-12 13:30发布

问题:

Trying to upload an image file (already existing) from a user's phone (Android) on his google drive via my app using drive API and Xamarin (C#). There are several solutions to upload but they all are showing to upload a new file.. for example

Google Drive API implementation Xamarin Android

Upload file into google drive folder using Xamarin.Android

both the solution given by @sushihangover create a new text file and then upload it via v3 API. I looked into the API as well but couldn't sort it out..

回答1:

upload image files using google drive Api

You could use the following codes to upload the image file to Google Drive :

DriveClass.DriveApi.NewDriveContents(client).SetResultCallback(new System.Action<IDriveApiDriveContentsResult>((result)=> {

            //Create MetadataChangeSet
            MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
                .SetTitle("Test.jpg")
                .SetMimeType("image/jpeg").Build();

            var contents = result.DriveContents;

            //push the bitmap data to DriveContents
            bitmapFromYourPicture.Compress(CompressFormat.Jpeg, 1, contents.OutputStream);
            IntentSender intentSender = DriveClass.DriveApi
                    .NewCreateFileActivityBuilder()
                    .SetInitialMetadata(metadataChangeSet)
                    .SetInitialDriveContents(contents)
                    .Build(client);

            StartIntentSenderForResult(intentSender, 2, null, 0, 0, 0);
        }));

If you choose the image picture by using intent you could get the picture Bitmap like this :

protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
    base.OnActivityResult(requestCode, resultCode, data);
    if (requestCode == 0)
    {
        var uri = data.Data;

        System.IO.Stream image_stream = ContentResolver.OpenInputStream(uri);
        Bitmap getBitmap = BitmapFactory.DecodeStream(image_stream);
    }
}