How to make the file shareable using google drive api

后端 未结 4 1148
悲哀的现实
悲哀的现实 2021-01-13 05:37

I am trying to get the file using google drive api, by default the file is not shareable i want to make it shareable.

Here is my code:-

    

        
相关标签:
4条回答
  • 2021-01-13 05:49

    The issue I was having was I did not enable the Google Drive API in my Google developer console and I did not load the 'client' library in order for gapi.client.request() to work properly with Google Picker.

    Below is a working example for a user to click a "share" button, authorize permission to their Google Drive, select multiple images or videos from the Picker modal, and return the file hyperlinks with 'anyone with the hyperlink can view' permissions.

    Prerequisites:

    • Setup your credentials in the Google developer console
      • Obtain your developer ID, client ID, and app ID
    • Enable both the Picker and Drive APIs in the developer console

    The javascript code:

    <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>

    Then the button to call everything in the HTML:

    <button onclick="onApiLoad()">Share via Google Drive</button>

    0 讨论(0)
  • 2021-01-13 05:51

    The Quickest way to obtain the preview of the file would be to append /preview at the end of Alternate link.

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

    You can then share that link to others.

    Found this here when i was testing out api requests on the drive api.

    0 讨论(0)
  • 2021-01-13 05:52

    Using the answer under this question did it for me: make folder shared google drive api v3?

    I applied it to 'file' rather than folder, made the type 'anyone' and role 'reader' - seems to be the equivalent of making the file shared.

    0 讨论(0)
  • 2021-01-13 05:57

    @arun you may want to read more about Permission resource in Drive API. For "shared" to be true, each file permission needs to specifies a role, type, and email address or domain. As an owner of the file (Docs, Sheets, etc.), you will need to provide the appropriate permission to be set to.

    Here is an example, using the Permissions.create (I recommend using Drive API v3)

    POST https://www.googleapis.com/drive/v3/files/{fileId}/permissions?key={YOUR_API_KEY}
    
    {
     "role": "reader",
     "type": "user",
     "emailAddress": "xxxxxxxx@xxx.com"
    }
    

    Response from the Drive Files.get:

    GET https://www.googleapis.com/drive/v3/files/{fileId}?fields=appProperties%2CfileExtension%2Ckind%2CmimeType%2Cshared&key={YOUR_API_KEY}
    
    
    {
     "kind": "drive#file",
     "mimeType": "application/vnd.google-apps.document",
     "shared": true
    }
    

    However, if you are unable to switch to the Drive v3, you can still use the Permission.insert from Drive v2 to do the job. Hope this helpful and good luck!

    0 讨论(0)
提交回复
热议问题