【问题标题】:How to get Google Sheet Id after sheet creation via API?通过 API 创建工作表后如何获取 Google 工作表 ID?
【发布时间】: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


【解决方案1】:
  • 当您上传文件时,您希望检索上传文件的文件 ID 和 URL。
  • 您想通过修改当前脚本来实现。

如果我的理解是正确的,那么这个修改呢?

修改点:

  • 为了返回文件 ID 和 URL,在这种情况下,使用这些字段。
    • exportLinks,id,kind,name,webContentLink,webViewLink
  • 为了从res 检索返回值,它使用res.json()

当上述修改点反映到你的脚本中时,变成如下。

修改脚本:

请按如下方式修改脚本的 2 部分。

从:
url.search = new URLSearchParams({ uploadType: 'multipart', fields: 'id,name,kind' });
到:
url.search = new URLSearchParams({ uploadType: 'multipart', fields: 'exportLinks,id,kind,name,webContentLink,webViewLink' });

从:
if (res.ok) {
  console.log(gapi)
  console.log(res)
到:
if (res.ok) {
  res.json().then((value) => {
    console.log(value)
  });

参考资料:

如果我误解了您的问题并且这不是您想要的方向,我深表歉意。

【讨论】:

  • 我能弄明白。我需要做的就是使用res.json().then(response => console.log(response.id)
  • @Intelligent 感谢您的回复。我很高兴你的问题得到了解决。根据您最新的问题和答案,我认为此修改可能是解决您的问题的提示。 stackoverflow.com/q/54697079
【解决方案2】:

您需要进行 2 处更改才能从文件中获取 URL:

1) 您必须在搜索参数中的字段之间添加 webViewLink 属性 [1]: url.search = new URLSearchParams({ uploadType: 'multipart', fields: 'id,name,kind,webViewLink' });

此属性是在网络中打开文件的链接。

2) 你得到的响应体是一个ReadableStream,你需要把它转换成一个你可以操作的json对象。这可以使用 json() 函数 [2] 对您获得的响应来完成,它将返回解析为具有以下属性的 Json 对象的响应主体:id、webViewLink 等。

我调整并测试了您的代码并按预期工作,在警报消息中显示了新创建文件的 URL:

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,webViewLink' });
try {

    const res = await fetch(url, {
        method: 'POST',
        headers: new Headers({ 'Authorization': 'Bearer ' + gapi.auth.getToken().access_token}),
        body: form
    });

    //Convert response to json
    const resJson = await res.json();

    if (res.ok) {
        console.log(gapi);
        console.log(res);
        console.log(resJson);
        alert(`"${excelFileName}" has successfully saved to your google drive!: ` + resJson.webViewLink);
    } else {
        console.error(`Encounter a problem saving excel file, ${excelFileName}, to google drive:` + res.Json);
    }
} catch (ex) {
    console.error(`Oops excel file for "${excelFileName}" wasn't saved. ${ex}`)
}

上面所有的代码当然都在一个同步函数里面,可以使用await语句。

[1]https://developers.google.com/drive/api/v3/reference/files#resource

[2]https://developer.mozilla.org/en-US/docs/Web/API/Body/json

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多