我正在尝试将 Google Drive 集成到我的 angular 应用程序中,以便我们的用户可以从文档中复制内容并将他们的图像下载到我的应用程序中。根据 file:get API Documentation ,我使用下面的代码来获取文件
var request = gapi.client.drive.files.get({
'fileId': fileId
});
var temp = this;
request.execute(function (resp) {
});
但在响应中,我只得到文件名和 ID。没有下载文件功能所需的下载 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);
}
}
我错过了什么吗?在客户端从云端硬盘下载文件是正确的方法吗?
最佳答案
问题 1:
如果我的理解是正确的,这个修改怎么样?请将此视为几种可能的答案之一。
修改点:
alt=media
对于查询参数。当这反射(reflect)到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:
在这种情况下,请使用如下所示的 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 文档的文件 ID。请注意这一点。 引用:
关于google-drive-api - 在 Javascript 客户端中从 Google Drive 下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60839431/