It's a story when using a shared drive with Google Drive API V3, because there was little information despite being super addicted, so make a note!
When I try to upload a file to a folder in the shared drive and move it by specifying the ID of the parent folder in meta.Parents
, for some reason I get the error File not found [folderid] 404
... ・
If you specify a folder ID in MyDrive that is not a shared drive as a trial, it will succeed, so there seems to be no problem with authentication and program flow.
Suddenly, I had to set the following two properties.
--meta object's DriveId
property
--CreateRequest object's SupportsAllDrives
property
DriveId, like the ID of the parent folder, is the last string of the URL when you open the root directory of the shared drive in your browser.
There is also a property called TeamDriveId
, but you can use DriveId instead of Deprecated
.
The overall code including authentication is now like ↓. It's almost a sample copy of Quick Start. (The code is C # SDK, but other SDKs will be the same)
GoogleDriveUploader.cs
string[] Scopes = { DriveService.Scope.DriveFile }; //DriveFile to upload
string ApplicationName = "Appropriate application name";
UserCredential credential;
using (var stream = new FileStream("client_secret_~~.apps.googleusercontent.com.json", FileMode.Open, FileAccess.Read))
{
string credPath = "token.json";
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
// Create Drive API service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
var meta = new Google.Apis.Drive.v3.Data.File()
{
Name = "File to create",
MimeType = "application/octet-stream", //Let's set appropriately
DriveId = "Shared drive ID(Like 0ABcDeJiHiJKLmn23)",
Parents = new List<string> { "Parent folder ID(Like 1auYhd9J9j ~)" }
};
using (var stream = new System.IO.FileStream("Full path of the file to upload", System.IO.FileMode.Open))
{
//New addition
var request = service.Files.Create(meta, stream, meta.MimeType);
request.Fields = "id, name";
request.SupportsAllDrives = true;
var ret = request.UploadAsync().Result;
if (ret.Status == Google.Apis.Upload.UploadStatus.Failed)
{
throw ret.Exception;
}
}
Recommended Posts