使用Google云端硬盘选择器(.Net)从Google云端硬盘检索文件时找不到文件异常

时间:2014-11-03 09:54:58

标签: c# .net google-drive-api google-picker

使用Google云端硬盘选择器(.Net)从Google云端硬盘检索文件时找不到文件异常

我在将Google Drive Picker放在我的页面上时遇到了问题。

picker self工作正常,我从选择器返回了一个fileid,但是当我尝试从服务器上的Google Drive下载所选文件时,根据给定的fileId,我收到一个'File not found'消息来自谷歌。

到目前为止我做了什么:

  • 创建了一个新的Google帐户;
  • 创建新项目;
  • 关于'API& “API”下的auth'部分,启用了Google Picker API,Drive API和Drive SDK;
  • 配置的驱动程序SDK在'API& '凭据'下的auth'部分,添加凭据/帐户;
  • 关于'API& “同意屏幕”下的“身份验证”部分,配置项目详细信息(Emailaddress,ProductName);
  • 为我的项目添加了.Net dll的Google客户端Api(https://www.nuget.org/packages/Google.Apis.Drive.v2/

以下帐户是在“凭据”部分下创建的:

  • Web应用程序的客户端ID(这里我配置了重定向URIS 和Javascript ORigins。我在Javascript上使用了这个客户端ID 客户端;
  • 服务帐户,在服务器端使用(我下载了由Google生成并在后面的代码中使用此Emailaddress的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.Apis.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]
]

0 个答案:

没有答案