如何使用 Google Drive API 通过 Javascript 下载文件 [英] How to use Google Drive API to download files with Javascript

查看:26
本文介绍了如何使用 Google Drive API 通过 Javascript 下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to download files from google drive with javascript API. I have managed to authenticate and load list of files using gapi.client.drive.files request. However, I stuck at downloading those files.
My attempt to download the file:

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

我在尝试运行上述程序时遇到这些错误:

I have these errors when trying to run the above:

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

(400) Bad Request

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

I recognize that the files which aren't google drive file (google doc, google slide) return the 403 error.
I am new to this. Any help and answer is really appreciated.

更新 0

来自关于处理 API 错误的 Google Drive 文档,这里是对 400 错误

From Google Drive documentation about Handling API Error, here is part of the explanation for 400 errors

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

This can mean that a required field or parameter has not been provided, the value supplied is invalid, or the combination of provided fields is invalid.

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

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

This is because I have alt:'media' in my parameter object.

I tried gapi.client.drive.files.export, but it doesn't work either and it returns (403) Insufficient Permission although my Google Drive account has the edit permission for those files. Here is my code:

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);
    });
});

更新 1

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

Based on abielita's answer, I have tried to make an authorized HTTP request but it doesn't download the file. It actually returns the file information in response and responseText attribute in the XMLHttpRequest object.

  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');
  }

______________________________________________________

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

I found out that I can actually retrieve URLs of all those files from the folder using files' webViewLink or webViewContent attributes.

  • 来自 Google Drive 类型的文件(Google Doc、Google Sheet、等...)将具有 webViewLink 属性.webViewLink 将打开Google 云端硬盘中的文件.

  • A file which is from Google Drive type (Google Doc, Google Sheet, etc...) will have webViewLink attribute. A webViewLink will open the file in Google Drive.

非 Google Drive 类型的文件将具有 webContentLink.一个webContentLink 将下载文件.

A non Google Drive type file will have webContentLink. A webContentLink will download the file.

我的代码:

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);
}

推荐答案

基于此 文档,如果您使用的是 alt=media,则需要向文件的 资源 URL 并包含查询参数 alt=media.

Based from this documentation, if you're using alt=media, you need to make an authorized HTTP GET request to the file's resource URL and include the query parameter alt=media.

GET https://www.googleapis.com/drive/v3/files/0B9jNhSvVjoIVM3dKcGRKRmVIOVU?alt=media
Authorization: Bearer ya29.AHESVbXTUv5mHMo3RYfmS1YJonjzzdTOFZwvyOAUVhrs

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

Check here the examples of performing a file download with our Drive API client libraries.

String fileId = "0BwwA4oUTeiV1UVNwOHItT0xfa2M";
OutputStream outputStream = new ByteArrayOutputStream();
driveService.files().get(fileId)
        .executeMediaAndDownloadTo(outputStream);

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

For the error (403) Insufficient Permission, maybe this is a problem with your access token, not with your project configuration.

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

The insufficient permissions error is returned when you have not requested the scopes you need when you retrieved your access token. You can check which scopes you have requested by passing your access_token to this endpoint: https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=ACCESS_TOKEN

检查这些链接:

Google 云端硬盘上传返回 - (403) 权限不足

请记住,您要上传到服务帐户的 google 驱动器帐户.如果您希望能够从您自己的 Google Drive 帐户中看到它,您将不得不插入权限.给自己访问权限

Remember you are uploading to the service accounts google drive account. If you want to be able to see it from your own Google drive account you are going to have to do an insert of the permissions. to give yourself access

这篇关于如何使用 Google Drive API 通过 Javascript 下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆