Javascript 如何在通过API创建工作表后获取Google工作表Id?

Javascript 如何在通过API创建工作表后获取Google工作表Id?,javascript,google-sheets,google-drive-api,Javascript,Google Sheets,Google Drive Api,我有一个方法,可以创建一张工作表并上传到谷歌硬盘。当用户点击“创建报告”按钮时,报告将被创建并上传到用户google drive。它工作得很好。但是,工作表保存到Google drive后,Google的响应既不包含工作表id,也不包含工作表URL。用户们说,当他们点击“创建报告”按钮时,他们希望google工作表在保存到他们的google驱动器后在一个新的选项卡中打开。他们不想进入驱动器手动打开文件。我在想,上传工作表后返回的响应应该至少包含工作表id或google drive中创建的资源的U

我有一个方法,可以创建一张工作表并上传到谷歌硬盘。当用户点击“创建报告”按钮时,报告将被创建并上传到用户google drive。它工作得很好。但是,工作表保存到Google drive后,Google的响应既不包含工作表id,也不包含工作表URL。用户们说,当他们点击“创建报告”按钮时,他们希望google工作表在保存到他们的google驱动器后在一个新的选项卡中打开。他们不想进入驱动器手动打开文件。我在想,上传工作表后返回的响应应该至少包含工作表id或google drive中创建的资源的URL。有没有人对如何实现我的目标有想法?我正在使用谷歌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}`)
            }


  • 上载文件时,您希望检索上载文件的文件ID和URL
  • 您希望通过修改当前脚本来实现
如果我的理解是正确的,这次修改怎么样

修改点:
  • 为了返回文件ID和URL,在本例中使用这些字段。
    • exportLinks、id、种类、名称、webContentLink、webViewLink
  • 为了从
    res
    检索返回的值,它使用
    res.json()
当上述修改点反映到脚本中时,它将变成如下所示

修改脚本: 请修改脚本的两部分,如下所示

发件人: 致: 及

发件人: 致: 参考资料:
如果我误解了你的问题,而这不是你想要的方向,我道歉。

  • 上载文件时,您希望检索上载文件的文件ID和URL
  • 您希望通过修改当前脚本来实现
如果我的理解是正确的,这次修改怎么样

修改点:
  • 为了返回文件ID和URL,在本例中使用这些字段。
    • exportLinks、id、种类、名称、webContentLink、webViewLink
  • 为了从
    res
    检索返回的值,它使用
    res.json()
当上述修改点反映到脚本中时,它将变成如下所示

修改脚本: 请修改脚本的两部分,如下所示

发件人: 致: 及

发件人: 致: 参考资料:

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

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

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

此属性是在web中打开文件的链接

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}`)
}
当然,上面的所有代码都在一个sync函数中,以便能够使用wait语句

[1]


[2]

要从文件中获取URL,您需要进行两项更改:

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

此属性是在web中打开文件的链接

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}`)
}
当然,上面的所有代码都在一个sync函数中,以便能够使用wait语句

[1]


[2]

您正在使用应用程序脚本上载文件?您希望应用程序脚本中的url或id正确吗?您可以在发出请求时发布代码吗?只是将代码添加到问题中。请查看您的标记,您使用的不是Google apps脚本,而是问题中提到的驱动API。您将有更好的机会获得答案。您正在使用应用程序脚本上载文件?您希望应用程序脚本中的url或id正确吗?您可以在发出请求时发布代码吗?只是将代码添加到问题中。请查看您的标记,您使用的不是Google apps脚本,而是问题中提到的驱动API。你会有更好的机会得到答案的。我能找到答案。获取工作表id所需要做的就是使用
res.json()。然后(response=>console.log(response.id)
@Intelligent感谢您的回复。我很高兴您的问题得到了解决。从您最近的问题和答案来看,我认为此修改可能是解决您问题的一个提示。我能够找到答案。要获得工作表id,我只需使用
res.json()。然后(response=>console.log(response.id)
@Intelligent感谢您的回复。我很高兴您的问题得到解决。从您最近的问题和答案来看,我认为此修改可能是解决您问题的一个提示。
if (res.ok) {
  console.log(gapi)
  console.log(res)
if (res.ok) {
  res.json().then((value) => {
    console.log(value)
  });
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}`)
}