7
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Google Drive API V3 で共有ドライブにアップロードしよう

Last updated at Posted at 2020-10-16

なぜか404 親フォルダが見つかりませんエラー

Google Drive API V3で共有ドライブを使うときの話です、超ハマったわりに情報が少なかったのでメモ!
共有ドライブ内のフォルダにファイルをアップロードしようとして、meta.Parentsに親フォルダのIDを指定して動かすと、なぜかFile not found [folderid] 404というエラーがかえってきてしまいます・・・
ためしに共有ドライブでないMyDrive内のフォルダIDを指定すると成功するので、認証やプログラムの流れは問題なさそうです。

共有ドライブのアップロードはひと手間

いきなり結論ですが、以下の2プロパティを設定する必要がありました。

  • metaオブジェクトのDriveIdプロパティ
  • CreateRequestオブジェクのSupportsAllDrivesプロパティ

DriveIdもURLからコピー

DriveIdは親フォルダのIDと同じく、ブラウザで該当の共有ドライブのルートディレクトリを開いたときのURLの末尾文字列です。
なおTeamDriveIdというプロパティもありますがDeprecated 変わりにDriveIdを使えとのことでした。

完成

認証を含んだ全体的なコードは↓のようになりました。
ほぼQuickStartのサンプルコピペですが。
(コードはC#のSDKですけど他のSDKも同じでしょう)

GoogleDriveUploader.cs
string[] Scopes = { DriveService.Scope.DriveFile }; // アップロードするのでDriveFile
string ApplicationName = "適当にアプリケーション名";

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 = "作成するファイル",
    MimeType = "application/octet-stream", // 適宜設定しましょう
    DriveId = "共有ドライブのID (0ABcDeJiHiJKLmn23 みたいな)",
    Parents = new List<string> { "親フォルダのID (1auYhd9J9j~みたいな)" }
};

using (var stream = new System.IO.FileStream("アップロードするファイルのフルパス", System.IO.FileMode.Open))
{
    // 新規追加
    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;
    }
}
7
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?