如何使用google drive api使文件可共享

时间:2016-03-24 10:48:34

标签: javascript google-drive-api drive google-picker gapi

我正在尝试使用google drive api获取该文件,默认情况下该文件不可共享我想让它可共享。

这是我的代码: -

    <script type="text/javascript" src="https://apis.google.com/js/api.js"></script>
<script src="https://apis.google.com/js/client.js"></script>
        // The Browser API key obtained from the Google Developers Console.
            // Replace with your own Browser API key, or your own key.
            var developerKey = 'XXXXXXXXXX_ff_NX66eb-XXXXXXXXXXX';

            // The Client ID obtained from the Google Developers Console. Replace with your own Client ID.
            var clientId = "XXXXXXXXXX-hs4ujaro5sc3d0g8qndtcq2tl279cfm1.apps.googleusercontent.com"

            // Replace with your own App ID. (Its the first number in your Client ID)
            var appId = "XXXXXXXXXX";
            // Scope to use to access user's Drive items.
            var scope = ['https://www.googleapis.com/auth/drive'];

            var pickerApiLoaded = false;
            var oauthToken;

                  $scope.addGoogleDriveFile = function() {
                    gapi.load('auth', {'callback': onAuthApiLoad});
                     gapi.load('picker', {'callback': onPickerApiLoad}); 
                    gapi.client.setApiKey(developerKey);     
                      }

        function onAuthApiLoad() {
                         window.gapi.auth.authorize(
                             {
                               'client_id': clientId,
                               'scope': scope,
                               'immediate': false
                             },
                             handleAuthResult);
                       }

                        function onPickerApiLoad() {
                          pickerApiLoaded = true;
                          createPicker();
                        }

                        function handleAuthResult(authResult) {
                          if (authResult && !authResult.error) {
                            oauthToken = authResult.access_token;
                            createPicker();
                          }
                        }

                        // Create and render a Picker object for searching images.
                        function createPicker() {
                          if (pickerApiLoaded && oauthToken) {
                            var view = new google.picker.View(google.picker.ViewId.DOCS);
                            var picker = new google.picker.PickerBuilder()
                                .enableFeature(google.picker.Feature.NAV_HIDDEN)
                                .setAppId(appId)
                                .setOAuthToken(oauthToken)
                                .addView(view)
                                .addView(new google.picker.DocsUploadView())
                                .setDeveloperKey(developerKey)
                                .setCallback(pickerCallback)
                                .build();
                             picker.setVisible(true);
                          }
                        }

                    // A simple callback implementation.
                    function pickerCallback(data) {
                      if (data.action == google.picker.Action.PICKED) {
                          console.log(data);
                       gapi.client.load('drive', 'v2').then(function() {
                            var request = gapi.client.drive.files.get({
                            'fileId': data.docs[0].id
                          });   
                           request.execute(function(resp) {
                             console.log(resp);
                          }); 
               });

                      }
                    }

我收到以下回复: -

{
 "kind": "drive#file",
 "id": "0B2Tb9btqdPGHeDl2NU5mYXRIaGc",
 "etag": "\"rCKCAyesbPCaBxGt0eDJcEBQNUI/MTQ1ODgxNDU0MDg2NA\"",
 "selfLink": "https://www.googleapis.com/drive/v2/files/0B2Tb9btqdPGHeDl2NU5mYXRIaGc",
 "webContentLink": "https://docs.google.com/uc?id=0B2Tb9btqdPGHeDl2NU5mYXRIaGc&export=download",
 "alternateLink": "https://drive.google.com/file/d/0B2Tb9btqdPGHeDl2NU5mYXRIaGc/view?usp=drivesdk",
 "iconLink": "https://ssl.gstatic.com/docs/doclist/images/icon_12_pdf_list.png",
 "thumbnailLink": "https://lh6.googleusercontent.com/iriNEeCbpP3OfCxntpc7sK7Dok03tcBJ86X4Be_sFgLXXG1Ta8b2WOM6pF6sEpS8ytaMvA
=s220",
 "title": "POTSS-2012.pdf",
 "mimeType": "application/pdf",
 "labels": {
  "starred": false,
  "hidden": false,
  "trashed": false,
  "restricted": false,
  "viewed": true
 },
 "createdDate": "2016-03-24T09:57:00.978Z",
 "modifiedDate": "2016-03-24T10:15:40.864Z",
 "modifiedByMeDate": "2016-03-24T09:57:00.978Z",
 "lastViewedByMeDate": "2016-03-24T09:57:00.978Z",
 "markedViewedByMeDate": "1970-01-01T00:00:00.000Z",
 "version": "130",
 "parents": [
  {
   "kind": "drive#parentReference",
   "id": "0AGTb9btqdPGHUk9PVA",
   "selfLink": "https://www.googleapis.com/drive/v2/files/0B2Tb9btqdPGHeDl2NU5mYXRIaGc/parents/0AGTb9btqdPGHUk9PVA"
,
   "parentLink": "https://www.googleapis.com/drive/v2/files/0AGTb9btqdPGHUk9PVA",
   "isRoot": true
  }
 ],
 "downloadUrl": "https://doc-0o-3g-docs.googleusercontent.com/docs/securesc/79n10ihd7kdei03rpq502qv5437nv33f
/b6p7kupn55cuqeqq8l0d9vc1orf4bkiv/1458813600000/07489391032112366212/07489391032112366212/0B2Tb9btqdPGHeDl2NU5mYXRIaGc
?e=download&gd=true",
 "userPermission": {
  "kind": "drive#permission",
  "etag": "\"rCKCAyesbPCaBxGt0eDJcEBQNUI/QKpDIyepJ3z6YHq0L3ksgvrZLSo\"",
  "id": "me",
  "selfLink": "https://www.googleapis.com/drive/v2/files/0B2Tb9btqdPGHeDl2NU5mYXRIaGc/permissions/me"
,
  "role": "owner",
  "type": "user"
 },
 "originalFilename": "POTSS-2012.pdf",
 "fileExtension": "pdf",
 "md5Checksum": "5b60cd94d0c0647c8828a60b8ce7efe4",
 "fileSize": "519097",
 "quotaBytesUsed": "519097",
 "ownerNames": [
  "xxxxx IT"
 ],
 "owners": [
  {
   "kind": "drive#user",
   "displayName": "xxxx IT",
   "isAuthenticatedUser": true,
   "permissionId": "07489391032112366212",
   "emailAddress": "it%xxxx .com@xxxxx.com"
  }
 ],
 "lastModifyingUserName": "xxxxx IT",
 "lastModifyingUser": {
  "kind": "drive#user",
  "displayName": "xxxx IT",
  "isAuthenticatedUser": true,
  "permissionId": "07489391032112366212",
  "emailAddress": "it%xxxx.com@xxxx.com"
 },
 "editable": true,
 "copyable": true,
 "writersCanShare": true,
 "shared": false,
 "explicitlyTrashed": false,
 "appDataContents": false,
 "headRevisionId": "0B2Tb9btqdPGHT0pGV1FRRis0MmlJVmZsOE5uMU5UK2FNR0g0PQ",
 "spaces": [
  "drive"
 ]
}

我希望更改&#34;分享&#34;:真实而不是&#34;分享&#34;:false

我如何更改其权限?

任何想法?

由于

4 个答案:

答案 0 :(得分:3)

@arun您可能想要阅读有关Drive API中Permission resource的更多信息。要&#34;分享&#34; true ,每个文件权限都需要指定roletype和{{1 }}。作为文件(文档,表格等)的所有者,您需要提供相应的权限才能设置。

以下是一个示例,使用Permissions.create(我建议使用Drive API v3

email address or domain

云端硬盘Files.get的响应:

POST https://www.googleapis.com/drive/v3/files/{fileId}/permissions?key={YOUR_API_KEY}

{
 "role": "reader",
 "type": "user",
 "emailAddress": "xxxxxxxx@xxx.com"
}

但是,如果您无法切换到云端硬盘v3,仍然可以使用云端硬盘v2中的Permission.insert来完成工作。希望这有用,祝你好运!

答案 1 :(得分:1)

获取文件预览的最快方法是在备用链接的末尾附加/preview

https://drive.google.com/file/d/0B2Tb9btqdPGHeDl2NU5mYXRIaGc/preview

一样

然后,您可以与其他人分享该链接。

当我在驱动器api上测试api请求时找到此here

答案 2 :(得分:1)

我遇到的问题是我没有在我的Google开发者控制台中启用Google Drive API而我没有加载“客户端”#39;库,以使gapi.client.request()与Google Picker一起正常工作。

以下是用户点击&#34;分享&#34;按钮,授权其Google云端硬盘的权限,从Picker模式中选择多个图片或视频,并返回文件超链接,其中任何人都可以查看&#39;权限。

先决条件:

    Google开发者控制台中的
  • Setup your credentials
    • 获取您的开发者ID,客户ID和应用ID
  • 在开发者控制台中启用Picker和Drive API

javascript代码:

&#13;
&#13;
<script type="text/javascript">
  // The API key obtained from the Google Developers Console.
  var developerKey = '#####';

  // The Client ID obtained from the Google Developers Console.
  var clientId = "####"

  // App ID. (Its the first number in your Client ID)
  var appId = "####";

  // Scope to use to access user's Drive items.
  var scope = ['https://www.googleapis.com/auth/drive'];

  var pickerApiLoaded = false;
  var oauthToken;

  // Use the Google API Loader script to load the google.picker script.
  function onApiLoad() {
    gapi.load('auth', {'callback': onAuthApiLoad});
    gapi.load('picker:client', {'callback': onPickerApiLoad});
  }

  function onAuthApiLoad() {
    window.gapi.auth.authorize(
      {
        'client_id': clientId,
        'scope': scope,
        'immediate': false
      },
      handleAuthResult);
  }

  function onPickerApiLoad() {
    pickerApiLoaded = true;
    createPicker();
  }

  function handleAuthResult(authResult) {
    if (authResult && !authResult.error) {
      oauthToken = authResult.access_token;
      createPicker();
    }
  }

  // Create and render a Picker object
  function createPicker() {
    if (pickerApiLoaded && oauthToken) {
      var view1 = new google.picker.DocsView(google.picker.ViewId.DOCS_IMAGES_AND_VIDEOS)
        .setIncludeFolders(true)
        .setSelectFolderEnabled(true);
      var picker = new google.picker.PickerBuilder()
        .enableFeature(google.picker.Feature.MULTISELECT_ENABLED)
        .addView(view1)
        .setAppId(appId)
        .setOAuthToken(oauthToken)
        .setDeveloperKey(developerKey)
        .setCallback(pickerCallback)
        .build();
      picker.setVisible(true);
    }
  }

  // A simple callback implementation.
  function pickerCallback(data) {
    var doc = "";
    var fileID = "";
    if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
      var gdurl = "";
      var type = "anyone";
      var role = "reader";
      for(var i = 0; i < data[google.picker.Response.DOCUMENTS].length; i++){
        doc = data[google.picker.Response.DOCUMENTS][i];
        gdurl = gdurl + " " + doc[google.picker.Document.URL];
        
        //change the file permissions to share with anyone with the link
        fileID = doc[google.picker.Document.ID];
        var request1 = gapi.client.request({
          'path': '/drive/v3/files/' + fileID + '/permissions',
          'method': 'POST',
          'headers': {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + oauthToken
          },
          'body':{
            'role': role,
            'type': type
          }
        });
        request1.execute(function(resp) {
          console.log(resp);
        });
      }
      // Form and display the message with hyperlinks included
      var message = 'Google Drive media link(s): ' + gdurl;
      alert('Success! Here are the hyperlinks for anyone to view: ' + message);
    }
  }
  </script>
&#13;
&#13;
&#13;

然后按钮调用HTML中的所有内容:

&#13;
&#13;
<button onclick="onApiLoad()">Share via Google Drive</button>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

使用这个问题的答案为我做了: make folder shared google drive api v3?

我将其应用于&#39;文件&#39;而不是文件夹,制作类型&#39;任何人&#39;和角色的读者&#39; - 似乎相当于使文件共享。