Downloading a file from Google Drive in Javascript client
Asked Answered
M

2

8

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?

Malaise answered 24/3, 2020 at 21:12 Comment(3)
I have to apologize for my poor English skill. Unfortunately, I cannot understand about your goal. So can I ask you about your question? You want to retrieve "download URL" of the file ID? Or you want to download a file of the file ID? Which do you want to achieve?Dudgeon
@Dudgeon I want to download the file.Malaise
Thank you for replying. From your replying, I proposed a modified script. Could you please confirm it? If I misunderstood your question and this was not the direction you want, I apologize.Dudgeon
D
12

Question 1:

  • You want to download a file from Drive API.
  • Your access token can be used for downloading the file.
  • You have the permission for downloading the file.
  • You are using the method of files.get in Drive API. In this case, the file is not Google Docs.
  • You want to achieve this using gapi with JavaScript.

If my understanding is correct, how about this modification?

Modification point:

  • In order to download a file using the method of files.get in Drive API, please use alt=media for the query parameter. When this is reflected to gapi, please add alt: "media" to the request object.

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:

  • You want to download Google Document as a DOCX format.

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.

});
  • In this case, fileId is the file ID of Google Document. Please be careful this.

Reference:

Dudgeon answered 25/3, 2020 at 4:34 Comment(2)
Thanks for the response. I'm able to get the image files by using the alt:"media". How can I get the Google Docs document content? I'm getting the error-> reason: "fileNotDownloadable" message: "Only files with binary content can be downloaded. Use Export with Google Docs files.".docx filesMalaise
@Malaise Thank you for replying. I'm glad your question was resolved. About your 2nd question, I added a sample script to my answer. Could you please confirm it? If that was not the direction you want, I apologize.Dudgeon
S
3

This is good for downloading an image

async function downloadFile(fileId: string, mimeType: string) {
        const res = await gapi.client.drive.files.get({
            fileId,
            alt: 'media'
        });
        const base64 = 'data:' + mimeType + ';base64,' + Buffer.from(res.body, 'binary').toString('base64');
        return base64;
    }
Southerland answered 18/1, 2021 at 11:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.