Upload file into google drive folder using Xamarin

2020-04-23 10:57发布

问题:

I want to create file inside a specific folder in google drive ( not the default location ) using Xamarin.Andriod

I'm using the below code

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

            DriveClass.DriveApi
                   .GetRootFolder(_googleApiClient)
                    .CreateFile(_googleApiClient, changeSetfile, contentResults.DriveContents);

回答1:

  1. Implement GoogleApiClient.IConnectionCallbacks

  2. Obtain a GoogleApiClient with DriveClass.API and DriveClass.ScopeFile

GoogleApiClient Example:

if (_googleApiClient == null) //  _googleApiClient is a class level variable
{
    _googleApiClient = new GoogleApiClient.Builder(this)
      .AddApi(DriveClass.API)
      .AddScope(DriveClass.ScopeFile)
      .AddConnectionCallbacks(this)
      .AddOnConnectionFailedListener(onConnectionFailed)
      .Build();
}
if (!_googleApiClient.IsConnected)
    _googleApiClient.Connect();
  1. Once connected, Query for folder, create if needed and then "write" a file to it.

Folder and File Example:

var folderName = "StackOverflow";
using (var driveId = DriveClass.DriveApi.GetRootFolder(_googleApiClient))
using (var query = new QueryClass.Builder().AddFilter(Filters.And(Filters.Eq(SearchableField.Title, folderName), Filters.Eq(SearchableField.Trashed, false))).Build())
using (var metaBufferResult = await driveId.QueryChildrenAsync(_googleApiClient, query))
{
    if (metaBufferResult.Status.IsSuccess)
    {
        DriveId folderId = null;
        foreach (var metaData in metaBufferResult.MetadataBuffer)
        {
            if (metaData.IsFolder && metaData.Title == folderName)
            {
                folderId = metaData.DriveId;
                break;
            }
        }

        IDriveFolder driveFolder = null;
        switch (folderId)
        {
            case null: // if folder not found, create it and fall through to default
                using (var folderChangeSet = new MetadataChangeSet.Builder().SetTitle(folderName).Build())
                using (var folderResult = await driveId.CreateFolderAsync(_googleApiClient, folderChangeSet))
                {
                    if (!folderResult.Status.IsSuccess)
                    {
                        Log.Error(TAG, folderResult.Status.StatusMessage);
                        break;
                    }
                    driveFolder = folderResult.DriveFolder;
                }
                goto default;
            default:
                driveFolder = driveFolder ?? folderId.AsDriveFolder();

                // create your file in the IDriveFolder obtained, 
                using (var contentResults = await DriveClass.DriveApi.NewDriveContentsAsync(_googleApiClient))
                {
                    if (contentResults.Status.IsSuccess)
                    {
                        using (var writer = new OutputStreamWriter(contentResults.DriveContents.OutputStream))
                        {
                            writer.Write("StackOverflow Rocks");
                            using (var changeSet = new MetadataChangeSet.Builder()
                                .SetTitle("StackOverflow Rocks")
                                .SetStarred(true)
                                .SetMimeType("text/plain")
                                .Build())
                            using (var driveFileResult = await driveFolder.CreateFileAsync(_googleApiClient, changeSet, contentResults.DriveContents))
                            {
                                if (driveFileResult.Status.IsSuccess)
                                    Log.Debug(TAG, "File created, open https://drive.google.com to review it");
                                else
                                    Log.Error(TAG, driveFileResult.Status.StatusMessage);
                            }
                        }
                    }
                }
                driveFolder.Dispose();
                break;
        }
        folderId?.Dispose();
    }
    else
    {
        Log.Error(TAG, metaBufferResult.Status.StatusMessage);
    }
}

Notes:

  • Do this on a background thread
  • Drive allows multiple files/folders with same name (Title)
    • Query for existing files if you want to replace one
    • Query for existing folders unless you really what multiple folders with the same Title
  • Folders and files in the Trash are returned queries unless excluded.
  • Make use of Using blocks and Dispose to avoid leaks