Exclude file not found when retrieving file from Google Drive using Google Drive Picker (.Net)

Not found file exception while fetching file from Google Drive using Google Drive (.Net)

I am facing issues while hosting Google Drive on my page.

The pickbox works fine, I got the file back from the picker, but when I try to download the selected file from Google Drive to the server based on the given file, I get a "File not found" message from Google.

What I have done so far:

  • Created a new google account;
  • A new project has been created;
  • In the "API and Out" section in the "API" section, the Google Picker API, Drive API and Drive SDK are enabled;
  • Configurable Drive SDK In the "API and Authorization" section in the "Credentials" section, add credentials / accounts;
  • In the "API and Authorization" section in the "Consent Screen" section, configure the project information (email address, username);
  • Added client api for .Net dll for my project ( https://www.nuget.org/packages/Google.Apis.Drive.v2/ )

The following accounts are created in the Credentials section:

  • Client ID for web application (Here I have configured URIS redirection and Javascript ORigins. I used this client ID in Javascript client side;
  • The service account used on the server side (I downloaded the P12 certificate as generated by Google and used that email in the code behind);

My client code (based on sample api in google drive)

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;
    }
}

      

Code for:

   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;
    } 

      

Mistake:

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]
]

      

+3


source to share





All Articles