在Javascript客户端中从Google云端硬盘下载文件

时间:2020-03-24 21:12:31

标签: google-drive-api google-docs-api google-photos-api

我正在尝试将Google云端硬盘集成到我的角度应用程序中,以便我们的用户可以复制文档中的内容并将其图像下载到我的应用程序中。根据{{​​3}},我正在使用以下代码来获取文件

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

但是在响应中我只得到文件名和ID.downloadFile函数不需要下载URL。 响应:

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

我错过了什么吗?从客户端的云端硬盘下载文件是正确的方法吗?

2 个答案:

答案 0 :(得分:3)

问题1:

  • 您要从云端硬盘API下载文件。
  • 您的访问令牌可用于下载文件。
  • 您具有下载文件的权限。
  • 您正在使用Drive API中的files.get方法。在这种情况下,该文件不是Google文档。
  • 您要使用带有Java的gapi实现此目的。

如果我的理解是正确的,那么该修改如何?请认为这只是几个可能的答案之一。

修改点:

  • 要使用Drive API中的files.get方法下载文件,请使用alt=media作为查询参数。当这反映到gapi时,请将alt: "media"添加到请求对象。

修改后的脚本:

修改脚本后,它如下所示。

从:
var request = gapi.client.drive.files.get({
        'fileId': fileId
    });
     var temp = this;
     request.execute(function (resp) {
});
至:
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.

});

参考:

问题2:

  • 您要以DOCX格式下载Google文档。

在这种情况下,请按以下方式使用files.export方法。

示例脚本:

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.

});
  • 在这种情况下,fileId是Google Document的文件ID。请注意这一点。

参考:

答案 1 :(得分:0)

这是下载图片的好方法

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