我正在尝试将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);
}
}
我错过了什么吗?从客户端的云端硬盘下载文件是正确的方法吗?
答案 0 :(得分:3)
如果我的理解是正确的,那么该修改如何?请认为这只是几个可能的答案之一。
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.
});
在这种情况下,请按以下方式使用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;
}