我正在尝试使用 Google 的 Picker API 获取文件的直接下载 URL,以便我可以选择一个文件并将该 URL 传递给服务器端代码以下载该项目的副本并将其存储在服务器上。
我可以通过选择器 API 进行授权并获取所选文件的信息,包括文件名和预览 URL(在 JSON 响应文档中简单地称为“此项目的 URL”:https://developers.google.com/picker/docs/results)
我注意到这里有一篇关于使用 Drive API 获取直接下载 URL 的帖子:Get google drive file download URL
但是,当我在选择器回调函数中执行此操作时(基于此处的文档:https://developers.google.com/picker/docs/)
我收到错误:
"Project [number here] is not found and cannot be used for API calls. If it is recently created, enable Drive API by visiting https://console.developers.google.com/apis/api/drive.googleapis.com/overview?project=[project number here] then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry."
我在开发者控制台中启用了 API,并将 URL 添加到了 JS 允许的来源。
文档非常困惑,似乎有 3 个版本的 REST API 可以与 Drive 一起使用,它基于 gapi.auth2 对象,而选择器 api 使用 gapi.auth 对象。
我不确定在执行 GET 请求之前是否需要使用 Google Drive API 再次进行身份验证。这一切看起来都很困惑,我相信一定有一种更简单的方法来满足简单的请求!
我的选择器回调函数:
pickerCallback: function(data) {
if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
var doc = data[google.picker.Response.DOCUMENTS][0];
var fileName = doc[google.picker.Document.NAME];
var url = doc[google.picker.Document.URL];
var docId = doc[google.picker.Document.ID];
var request = null;
gapi.client.load('drive', 'v2', function() {
request = gapi.client.drive.files.get({
'fileId': docId
});
request.execute(function(resp){
console.log(resp);
});
});
//Write upload details to page
//Populate hidden field
}
最佳答案
您可能想尝试 documentation 中显示的简单回调实现。请注意,url
是在 if
语句之前初始化的:
function pickerCallback(data) {
var url = 'nothing';
if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
var doc = data[google.picker.Response.DOCUMENTS][0];
url = doc[google.picker.Document.URL];
}
var message = 'You picked: ' + url;
document.getElementById('result').innerHTML = message;
}
此外,在授权时,设置 AppId
值并选择具有应用当前 OAuth 2.0 token 的用户帐户。请注意,AppId
集和用于授权访问用户文件的客户端 ID 必须包含在同一应用中。然后,成功获取fileId
后,就可以使用files.get
发送请求了。 。默认情况下,这会响应 Files resource在响应正文中,其中包含 downloadUrl
。
有关更多见解,请参阅相关的 SO post .
关于javascript - 如何从 Google Picker JavaScript API 获取直接下载 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44412969/