非常に便利なGoogle Drive。
ブラウザからも利用も簡単ですし、Drive API を利用すれば慣れ親しんだ.NETプログラムでファイル操作ができちゃいます。
導入方法からサンプルプログラムが充実しており、認証やファイルのダウンロードはすぐに始めることができます。
しかし、アップロードしようとすると、いきなり躓いてしましました。
指定フォルダにアップロードするにあたり、こちらのページを参照しました。
https://developers.google.com/drive/v3/web/folder
ローカルファイルのアップロードを行いたいので「Inserting a file in a folder」の.NETの項目まで移動します。コードをそのまま引用すると...
var folderId = "0BwwA4oUTeiV1TGRPeTVjaWRDY1E";
var fileMetadata = new File()
{
Name = "photo.jpg",
Parents = new List<string>
{
folderId
}
};
FilesResource.CreateMediaUpload request;
using (var stream = new System.IO.FileStream("files/photo.jpg",
System.IO.FileMode.Open))
{
request = driveService.Files.Create(
fileMetadata, stream, "image/jpeg");
request.Fields = "id";
request.Upload();
}
var file = request.ResponseBody;
Console.WriteLine("File ID: " + file.Id);
出典:https://developers.google.com/drive/v3/web/folder
(folderIdはドライブIDとして、また、アップロード対象のファイルパスも適宜変更してください)
17行目のUpload()メソッドで実行するのですが、この戻り値でExceptionが発生。Messageは
"Google.Apis.Requests.RequestError\r\nInsufficient Permission [403]\r\nErrors [\r\n\tMessage[Insufficient Permission] Location[ - ] Reason[insufficientPermissions] Domain[global]\r\n]\r\n"
のような頭の痛い感じ。
domainにアップロードしようとしていたので、特別な権限がいるんだろうか…と数日頭を捻り続けましたが、答えはひょんな所から降ってきました。
scopeを確認しよう
stackoverflowなどを読み漁ると、scopeに〇〇を追加しろ!のようなことが書かれていますが、後付けのscopeなどどうやって追加していいのか皆目見当がつきません。
そうなんです。後付けできないんですよ。(方法がないというわけではなく、知らないだけです)
つまり、認証の段階で得たscopeがそもそも間違っているのではないかという疑問に達したのです。
ソースを確認してみます。
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Drive.v3.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace DriveQuickstart
{
class Program
{
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/drive-dotnet-quickstart.json
static string[] Scopes = { DriveService.Scope.DriveReadonly };
static string ApplicationName = "Drive API .NET Quickstart";
static void Main(string[] args)
{
UserCredential credential;
using (var stream =
new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart.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,
});
// Define parameters of request.
FilesResource.ListRequest listRequest = service.Files.List();
listRequest.PageSize = 10;
listRequest.Fields = "nextPageToken, files(id, name)";
// List files.
IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute()
.Files;
Console.WriteLine("Files:");
if (files != null && files.Count > 0)
{
foreach (var file in files)
{
Console.WriteLine("{0} ({1})", file.Name, file.Id);
}
}
else
{
Console.WriteLine("No files found.");
}
Console.Read();
}
}
}
出典:https://developers.google.com/drive/v3/web/quickstart/dotnet
いました…20行目。しかと
static string[] Scopes = { DriveService.Scope.DriveReadonly };
とあるじゃないですか。
こちらを
static string[] Scopes = { DriveService.Scope.DriveFile };
と直して、再認証すればアップロードが可能になったとさ。
認証ファイルはサンプルのままだと
C:\Users\(ユーザー名)\Documents\.credentials\drive-dotnet-quickstart.json
にあります。jsonファイルを削除し、プロジェクト(exeファイル)を実行すると再認証されます