Nodejs Google Drive API可共享链接

时间:2017-11-23 04:55:32

标签: javascript node.js google-drive-api google-apis-explorer

对于我的Nodejs项目,我正在使用Google驱动器API进行文件共享。但问题是,我从API获得的URL不是可共享的链接。所以我必须去驱动器并打开共享。有没有办法获得可共享链接或使用java脚本代码切换共享?请给我一个解决方案。

1 个答案:

答案 0 :(得分:0)

这些评论确实很有帮助,此解决方案适用于Google云端硬盘的v3和Google Doc v1。我正在对服务帐户使用jwt身份验证,并且使用Drive v2的alternativeLink无法共享。

我假设身份验证过程已知且已完成。我正在以块形式编写代码,因此读者可以选择使用await,promise或callbacks

首先,您需要创建一个文档:

google.docs({version: 'v1', auth});
docs.documents.create({title: "Your Title"}, (error, response) => {
    if (error) return;
    //So now you have the documentId
    const {data: {documentId}} = response;
});

现在使用documentId,我们需要为文档添加权限。 键是向任何人授予权限。该文档说明anyone不需要电子邮件或用户。

const resource = {"role": "reader", "type": "anyone"};
drive.permissions.create({fileId:documentId, resource: resource}, (error, result)=>{
    if (error) return;
    //If this work then we know the permission for public share has been created 
});

现在我们已经准备就绪,我们只需要URL。很高兴可共享的网址具有稳定的格式,因此我们可以自行编写它,而无需额外的请求:

https://docs.google.com/document/d/${documentId}}/view

Node.js Google Api会快速更改,如果有任何混淆,我正在使用"googleapis": "^38.0.0",