4

Google ドライブ ピッカー (.Net) を使用して Google ドライブからファイルを取得中に、ファイルが見つからないという例外が発生する

ページに Google ドライブ ピッカーを配置する際に問題が発生しました。

ピッカー自体は正常に動作しています。ピッカーからファイル ID が返されましたが、サーバー上の Google ドライブから選択したファイルをダウンロードしようとすると、指定されたファイル ID に基づいて、Google から「ファイルが見つかりません」というメッセージが表示されます。

私がこれまでに行ったこと:

  • 新しい Google アカウントを作成しました。
  • 新しいプロジェクトを作成しました。
  • 「APIs」の下の「APIs & auth」セクションで、Google Picker API、Drive API、および Drive SDK を有効にしました。
  • 構成された Drive SDK [資格情報] の下の [APIs & auth] セクションで、資格情報 /accounts を追加します。
  • [同意画面] の下の [API と認証] セクションで、プロジェクトの詳細 (メールアドレス、製品名) を構成します。
  • .Net dll 用の Google Client Api をプロジェクトに追加しました ( https://www.nuget.org/packages/Google.Apis.Drive.v2/ )

次のアカウントが「資格情報」セクションの下に作成されます。

  • Web アプリケーションのクライアント ID (ここでは、リダイレクト URIS と Javascript ORigins を構成しました。クライアント側の Javascript でこのクライアント ID を使用しました。
  • サーバー側で使用されるサービス アカウント (Google によって生成された P12 証明書をダウンロードし、コード ビハインドでこのメールアドレスを使用しました);

クライアント側のコード (Google Drive API サンプルに基づく)

var developerKey = '<api_key>';
var clientId = '<client_id>';
var appId = '<app_id>';
var scope = <scopes (drive.readonly and drive.file>;
var apiLoaded = false;

var pickerApiLoaded = false;
var oauthToken;

// Use the API Loader script to load google.picker and gapi.auth.
function onApiLoad() {
    apiLoaded = true;
}

function onPickerClick() {
    gapi.load('auth', { 'callback': onAuthApiLoad });
    gapi.load('picker', { 'callback': onPickerApiLoad });
}

function onAuthApiLoad() {
    window.gapi.auth.authorize(
        {
            'client_id': clientId,
            'scope': scope,
            'immediate': false
        },
        handleAuthResult);
}

function onPickerApiLoad() {
    pickerApiLoaded = true;
    createPicker();
}

function handleAuthResult(authResult) {
    if (authResult && !authResult.error) {
        oauthToken = authResult.access_token;
        createPicker();
    }
}

function createPicker() {
    if (pickerApiLoaded && oauthToken) {
        var picker = new google.picker.PickerBuilder().
            setAppId(appId).
            addView(google.picker.ViewId.DOCUMENTS).
            setOAuthToken(oauthToken).
            setDeveloperKey(developerKey).
            setCallback(pickerCallback).
            build();

        picker.setVisible(true);
    }
}

function pickerCallback(data) {
    if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
        var doc = data[google.picker.Response.DOCUMENTS][0];

        var fileName = document.getElementById('<%= HiddenFieldFileName.ClientID%>');
        fileName.value = doc.name;

        var fileId = document.getElementById('<%= HiddenFieldFileId.ClientID%>');
        fileId.value = doc.id;
    }
}

分離コード:

   public IExternalFile GetFile()
    {
        var fileId = HiddenFieldFileId.Value;
        if (!string.IsNullOrWhiteSpace(fileId))
        {
            try
            {
                var accountEmail = "<email setting from service account>";
                var certificatePath = "<path to the service account certificate>";
                var certificate = new X509Certificate2(certificatePath, "notasecret", X509KeyStorageFlags.Exportable);

                var serviceAccount =
                    new ServiceAccountCredential(new ServiceAccountCredential.Initializer(accountEmail)
                        {
                            Scopes = new[] {DriveService.Scope.DriveFile, DriveService.Scope.DriveReadonly}
                        }.FromCertificate(certificate));

                // Create the service.
                var service = new DriveService(new BaseClientService.Initializer()
                    {
                        HttpClientInitializer = serviceAccount,
                        ApplicationName = "<application name, configured in the Google Project"
                    });

                var file = service.Files.Get(fileId).Execute();
                var content = service.HttpClient.GetByteArrayAsync(file.DownloadUrl).Result;
                var size = (content != null) ? content.Length : 0;
                return new ExternalFile(file.OriginalFilename, size, content);
            }
            catch (Exception ex)
            {
                // error handling
            }
        }

        return null;
    } 

エラーメッセージ:

Google.Api.Requests.RequestError

File not found: <fileId> [404]
Errors [
Message[File not found: <fileId>] Location[ - ] Reason[notFound] Domain[global]
]
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: Google.GoogleApiException: Google.Apis.Requests.RequestError
File not found: <fileId> [404]
Errors [
Message[File not found: <fileId>] Location[ - ] Reason[notFound] Domain[global]
]
4

0 に答える 0