【发布时间】:2019-06-25 14:03:19
【问题描述】:
我有一种方法可以创建工作表并将其上传到 Google 云端硬盘。当用户单击显示“创建报告”的按钮时,将创建报告并将其上传到用户谷歌驱动器。它工作得很好。但是,将工作表保存到谷歌驱动器后来自谷歌的响应不包含工作表 ID 或工作表 URL。用户说当他们点击“创建报告”按钮时,他们希望谷歌表格在保存到他们的谷歌驱动器后在新标签中打开。他们不想进入驱动器手动打开文件。我在想,在上传工作表后返回的响应将至少包含工作表 ID 或在谷歌驱动器中创建的资源的 URL。有没有人知道如何完成我正在做的事情?我正在使用 Google API 将文件上传到用户驱动器。
这是上传工作表后发送的响应
"https://www.googleapis.com/upload/drive/v3/files?
uploadType=multipart&fields=id%2Cname%2Ckind", redirected: false,
status: 200, ok: true, …}
body: ReadableStream
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: ""
type: "cors"
url: "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id%2Cname%2Ckind"
//Here is the code:
let metadata = {
name: excelFileName,
mimeType: "application/vnd.google-apps.spreadsheet",
};
let form = new FormData();
form.append('metadata', new Blob([JSON.stringify(metadata)], { type: 'application/json' }));
form.append('file', excelFile);
let url = new URL('https://www.googleapis.com/upload/drive/v3/files');
url.search = new URLSearchParams({ uploadType: 'multipart', fields: 'id,name,kind' });
try {
let res = await fetch(url, {
method: 'POST',
headers: new Headers({ 'Authorization': 'Bearer ' + gapi.auth.getToken().access_token }),
body: form
});
if (res.ok) {
console.log(gapi)
console.log(res)
alert(`"${excelFileName}" has successfully saved to your google drive!`);
} else {
console.error(`Encounter a problem saving excel file, ${excelFileName}, to google drive`);
}
} catch (ex) {
console.error(`Oops excel file for "${excelFileName}" wasn't saved. ${error}`)
}
【问题讨论】:
-
您正在使用应用脚本上传文件?您想要应用脚本中的 url 或 id 吗?您可以在提出请求时发布您的代码吗?
-
刚刚将代码添加到问题中。
-
请检查您的标签,您没有使用 Google 应用程序脚本,而是使用您的问题中提到的驱动 API。您将有更好的机会得到答案。
标签: javascript google-sheets google-drive-api