【发布时间】:2016-09-08 02:13:04
【问题描述】:
有什么方法可以使用 Google Drive API v3 获取本机文件(Google Docs)的内容?我知道 API v2 通过 exportLinks 属性支持此功能,但它不再起作用或已被删除。
【问题讨论】:
-
虽然一些答案适用于获取本地谷歌文档的最新版本,但我找不到本地谷歌文档修订版的导出
标签: google-drive-api
有什么方法可以使用 Google Drive API v3 获取本机文件(Google Docs)的内容?我知道 API v2 通过 exportLinks 属性支持此功能,但它不再起作用或已被删除。
【问题讨论】:
标签: google-drive-api
您还可以使用文件的webContentLink 属性在云端硬盘中下载包含二进制内容的文件(非谷歌驱动器文件)。来自https://developers.google.com/drive/v3/reference/files:
用于在浏览器中下载文件内容的链接。这是 仅适用于云端硬盘中包含二进制内容的文件。
一个例子(我使用方法get()从我的文件中检索webContentLink):
gapi.client.drive.files.get({
fileId: id,
fields: 'webContentLink'
}).then(function(success){
var webContentLink = success.result.webContentLink; //the link is in the success.result object
//success.result
}, function(fail){
console.log(fail);
console.log('Error '+ fail.result.error.message);
})
使用google驱动文件,可以使用导出方法来获取这些文件:https://developers.google.com/drive/v3/reference/files/export
此方法需要一个具有 2 个必需属性(fileId 和 mimeType)的对象作为参数。
可以查看mimeTypes 的可用列表here 或here(感谢@ravioli)
例子:
gapi.client.drive.files.export({
'fileId' : id,
'mimeType' : 'text/plain'
}).then(function(success){
console.log(success);
//success.result
}, function(fail){
console.log(fail);
console.log('Error '+ fail.result.error.message);
})
您可以使用gapi.client.drive.files.get 和alt:"media" 读取非谷歌文档文件内容(例如文本文件)。 Official example。我的例子:
function readFile(fileId, callback) {
var request = gapi.client.drive.files.get({
fileId: fileId,
alt: 'media'
})
request.then(function(response) {
console.log(response); //response.body contains the string value of the file
if (typeof callback === "function") callback(response.body);
}, function(error) {
console.error(error)
})
return request;
}
【讨论】:
GET webContentLink 时,您提供的第一个解决方案由于 CORS 而失败。第三个选项返回原始字符串中的内容,其中包含文件内容和一些包含在 WebkitFormBoundary 中的附加信息,我不确定如何正确解析。我应该提到我的应用程序是纯粹的客户端浏览器应用程序。
@noogui的答案。
对于v3的api,可以使用导出方式https://developers.google.com/drive/v3/reference/files/export
【讨论】:
如果您使用files.export,您将无法获得任何链接,可让您下载v3 Migration guide 中所述的文件。
例如使用 try-it,我只得到一个 MiMetype 响应,但没有可下载的链接:
[application/vnd.oasis.opendocument.text data]
解决方法是直接下载。只需将FILE_ID 替换为您的Google Doc 文件ID 并在浏览器中执行。通过这个,我能够导出 Google 文档文件。
https://docs.google.com/document/d/FILE_ID/export?format=doc
感谢labnol's guide 提供解决方法。
【讨论】: