google-drive-apigoogle-docs-apigoogle-photos-api

Downloading a file from Google Drive in Javascript client


I'm trying to integrate the Google Drive in my angular application So that our users can copy the content from docs and download their images to my application. As per the file:get API Documentation, I'm using the below code to get the file

var request = gapi.client.drive.files.get({
        'fileId': fileId
    });
     var temp = this;
     request.execute(function (resp) {
});

But in the response I'm getting only File name and ID.There is no download URL which is required for downloadFile function. Response:

{kind: "drive#file", 
  id: "1KxxxxxxxxxxxxxxycMcfp8YWH2I",
   name: " Report-November", 
   mimeType: "application/vnd.google-apps.spreadsheet", 
    result:{
kind: "drive#file"
id: "1K7DxawpFz_xiEpxxxxxxxblfp8YWH2I"
name: "  Report-November"
mimeType: "application/vnd.google-apps.spreadsheet"
  }
}



Download File Function:

/**
 * Download a file's content.
 *
 * @param {File} file Drive File instance.
 * @param {Function} callback Function to call when the request is complete.
 */
 downloadFile(file, callback) {
    if (file.downloadUrl) {
        var accessToken = gapi.auth.getToken().access_token;
        var xhr = new XMLHttpRequest();
        xhr.open('GET', file.downloadUrl);
        xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
        xhr.onload = function () {
            callback(xhr.responseText);
        };
        xhr.onerror = function () {
            callback(null);
        };
        xhr.send();
    } else {
        callback(null);
    }
}

Am I missing anything? Is it the right approach to download a file from Drive in the client side?


Solution

  • Question 1:

    If my understanding is correct, how about this modification?

    Modification point:

    Modified script:

    When your script is modified, it becomes as follows.

    From:

    var request = gapi.client.drive.files.get({
            'fileId': fileId
        });
         var temp = this;
         request.execute(function (resp) {
    });
    

    To:

    gapi.client.drive.files.get({
      fileId: fileId,
      alt: "media"
    }).then(function(res) {
    
      // In this case, res.body is the binary data of the downloaded file.
    
    });
    

    Reference:

    Question 2:

    In this case, please use the files.export method as follows.

    Sample script:

    gapi.client.drive.files.export({
      fileId: fileId,
      mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
    }).then(function(res) {
    
      // In this case, res.body is the binary data of the downloaded file.
    
    });
    

    Reference: