如何使用 Google Drive API 通过 Javascript 下载文件

phu*_*win 8 javascript google-api google-drive-api

我想使用 javascript API 从谷歌驱动器下载文件。我已经设法使用gapi.client.drive.files请求来验证和加载文件列表。但是,我坚持下载这些文件。
我尝试下载文件:

var request = gapi.client.drive.files.get({
        fileId:id,
        alt:'media'
});
request.execute(function(resp){
        console.log(resp);
});
Run Code Online (Sandbox Code Playgroud)

尝试运行上述程序时出现以下错误:

(403) The user has not granted the app 336423653212 read access to the file 0B0UFTVo1BFVmeURrWnpDSloxQlE.

(400) Bad Request
Run Code Online (Sandbox Code Playgroud)

我认识到不是谷歌驱动器文件(谷歌文档,谷歌幻灯片)的文件返回 403 错误。
我是新来的。任何帮助和答案都非常感谢。

更新 0

从 Google Drive 文档中关于处理 API 错误,这里是部分解释400 errors

这可能意味着未提供必填字段或参数、提供的值无效或提供的字段组合无效。

这是因为alt:'media'我的参数对象中有。

我试过了gapi.client.drive.files.export,但它也不起作用,(403) Insufficient Permission尽管我的 Google Drive 帐户具有对这些文件的编辑权限,但它仍会返回。这是我的代码:

var request = gapi.client.drive.files.get({
    fileId:element.id,
});
request.then(function(resp){
    console.log(resp.result);
    type = resp.result.mimeType;
    id = resp.result.id;
    var request = gapi.client.drive.files.export({
        fileId:id,
        mimeType:type
    })
    request.execute(function(resp){
        console.log(resp);
    });
});
Run Code Online (Sandbox Code Playgroud)

更新 1

根据abielita 的回答,我尝试发出授权的 HTTP 请求,但它没有下载文件。它实际上返回对象中的文件信息responseresponseText属性XMLHttpRequest

  function test() {
    var accessToken = gapi.auth.getToken().access_token;
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "https://www.googleapis.com/drive/v3/files/"+'1A1RguZpYFLyO9qEs-EnnrpikIpzAbDcZs3Gcsc7Z4nE', true);
    xhr.setRequestHeader('Authorization','Bearer '+accessToken);
    xhr.onload = function(){
        console.log(xhr);
    }
    xhr.send('alt=media');
  }
Run Code Online (Sandbox Code Playgroud)

______________________________________________________

我发现我实际上可以使用文件webViewLinkwebViewContent属性从文件夹中检索所有这些文件的 URL 。

  • 来自 Google Drive 类型(Google Doc、Google Sheet 等)的文件将具有webViewLink属性。AwebViewLink将在 Google Drive 中打开文件。

  • 非 Google Drive 类型的文件将具有webContentLink. A webContentLink将下载文件。

我的代码:

var request = gapi.client.drive.files.list({
    q:"'0Bz9_vPIAWUcSWWo0UHptQ005cnM' in parents", //folder ID
    'fields': "files(id, name, webContentLink, webViewLink)"
  });
request.execute(function(resp) {
        console.log(resp);
}
Run Code Online (Sandbox Code Playgroud)

abi*_*ita 8

根据此文档,如果您正在使用alt=media,则需要向文件发出授权的 HTTP GET 请求resource URL并包含查询参数alt=media

GET https://www.googleapis.com/drive/v3/files/0B9jNhSvVjoIVM3dKcGRKRmVIOVU?alt=media
Authorization: Bearer ya29.AHESVbXTUv5mHMo3RYfmS1YJonjzzdTOFZwvyOAUVhrs
Run Code Online (Sandbox Code Playgroud)

在此处查看使用我们的 Drive API 客户端库执行文件下载的示例。

String fileId = "0BwwA4oUTeiV1UVNwOHItT0xfa2M";
OutputStream outputStream = new ByteArrayOutputStream();
driveService.files().get(fileId)
        .executeMediaAndDownloadTo(outputStream);
Run Code Online (Sandbox Code Playgroud)

对于错误(403) Insufficient Permission,这可能是您的访问令牌问题,而不是您的项目配置问题。

如果您在检索访问令牌时未请求所需的范围,则会返回权限不足错误。您可以通过将您的 access_token 传递到此端点来检查您请求的范围:https : //www.googleapis.com/oauth2/v1/tokeninfo? access_token = ACCESS_TOKEN

检查这些链接:


Roc*_*coB 7

Phu,你离我太近了!

感谢您分享使用 webContentLink 和 webViewLink 的方法。我认为这最适合大多数目的。但是在我的应用程序中,我无法使用 viewContentLink,因为需要能够将图像输入画布,而 google 提供的图像还没有准备好 CORS。

所以这里有一个方法

var fileId = '<your file id>';
var accessToken = gapi.auth2.getAuthInstance().currentUser.get().getAuthResponse().access_token;// or this: gapi.auth.getToken().access_token;
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://www.googleapis.com/drive/v3/files/"+fileId+'?alt=media', true);
xhr.setRequestHeader('Authorization','Bearer '+accessToken);
xhr.responseType = 'arraybuffer'
xhr.onload = function(){
    //base64ArrayBuffer from https://gist.github.com/jonleighton/958841
    var base64 = 'data:image/png;base64,' + base64ArrayBuffer(xhr.response);

    //do something with the base64 image here

}
xhr.send();
Run Code Online (Sandbox Code Playgroud)

请注意,我将响应类型设置为arraybuffer,并向上移动alt=mediaxhr.open呼叫。我还从https://gist.github.com/jonleighton/958841 获取了一个将数组缓冲区转换为 base64 的函数。