使用Javascript客户端从Google云端硬盘下载文件

问题描述 投票:0回答:1

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

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

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

google-drive-api google-docs-api google-photos-api
1个回答
0
投票
  • 您要从Drive 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.

});

参考:

© www.soinside.com 2019 - 2024. All rights reserved.