在 Javascript 客户端中从 Google Drive 下载文件

VBC*_*VBC 2 google-docs-api google-drive-api google-photos-api

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

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

但在响应中,我只得到文件名和 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"
  }
}



Run Code Online (Sandbox Code Playgroud)

下载文件功能:

/**
 * 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Tan*_*ike 9

问题 1:

  • 您想从 Drive API 下载文件。
  • 您的访问令牌可用于下载文件。
  • 您有下载文件的权限。
  • 您正在使用 Drive API 中的 files.get 方法。在这种情况下,该文件不是 Google 文档。
  • 您想使用带有 Javascript 的 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) {
});
Run Code Online (Sandbox Code Playgroud) 到:
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.

});
Run Code Online (Sandbox Code Playgroud)

参考:

问题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.

});
Run Code Online (Sandbox Code Playgroud)
  • 在本例中,fileId是 Google 文档的文件 ID。请注意这一点。

参考: