How to insert file to a shared drive using REST on Apps Script?

与世无争的帅哥 提交于 2020-06-01 07:37:04

问题


Is there a way that we can upload files to shared drive using POST Method? I don't know how to call the Drive ID of the shared drive and target it to the URL fetch function, is this possible?

This is my code:

var DriveScope = 'https://www.googleapis.com/auth/drive';
var ServiceAccountPrivateKey ="-----BEGIN PRIVATE KEY----"
var ServiceAccountEmail = "drive-uploads@xxxxxxx.com";

function testinRest(){
var service = getDriveService();

var driveID = "XXXXXXXX";
var APIKey = "XXXXXXXXXXXXX";

var resumeBlob = Utilities.newBlob('Hire me!', 'text/plain', 'resume.txt');
var formData = {
  'name': 'Bob Smith',
  'email': 'bob@example.com',
  'resume': resumeBlob
};

  var url = 'https://www.googleapis.com/drive/v3/drives';
  var output = UrlFetchApp.fetch(url, {
    method: 'get',
    headers: { 'Authorization': 'Bearer ' + service.getAccessToken() },
    contentType: 'application/json'
  }).getContentText();  

  var response= JSON.parse(output);

  for(var i=0; i < response.drives.length; i++){

    if(driveID == response.drives[i].id){
      service.reset()
      if (service.hasAccess()) {
        var newPresentationName = "RJ POGI";
        var url = 'https://www.googleapis.com/upload/drive/v3/files?supportsAllDrives=true&key=' + APIKey;
        var body = {
          "name": newPresentationName,
          "parents": [driveID]
        };
        var params = {
          headers: {
            Authorization: 'Bearer ' + service.getAccessToken(),
            Referer:'https://explorer.apis.google.com' 
          },

          method: 'post',
          payload: formData,//JSON.stringify(body),
          contentType: 'application/json',
          muteHttpExceptions: true
        };
        var response = UrlFetchApp.fetch(url, params).getContentText();
        Logger.log('response: ' + response);
        var id = JSON.parse(response).id;
        return id;
      }
    }

}

}

function getDriveService(){
  var service = OAuth2.createService('drive').setTokenUrl('https://accounts.google.com/o/oauth2/token').setPrivateKey(ServiceAccountPrivateKey).setClientId(ServiceAccountEmail).setPropertyStore(PropertiesService.getUserProperties()).setScope(DriveScope);
  //console.log("Service::" + service);
  //console.log('Service Has Access::' + service.hasAccess()); 
  if (!service.hasAccess()) {
    Logger.log('Authentication error: %s', service.getLastError());
    return;
  }else{
     return service;
  }

}

function reset() {
  var service = getDriveService();
  service.reset();
}

On this example, I want the resumeBlob to be inserted on the targeted DriveID. Any help will be appreciated. Thanks!


回答1:


  • Your problem needs to be divided in three steps:

    1. Create a file on the drive with UrlFetchApp
    2. Pass a content to the file
    3. Insert the file into a shared drive

  • Now, you original question - 3. is easy to solve, you just need to specify in your requestsupportsTeamDrives=true.

  • More difficult is the combination of 1. and 2..

  • The Files: create method offers either an URI for media upload only requests, or for metadata-only.

  • The workaround would be to perform a resumable Upload, which allows you to post the metadata first, and add the file contents later.

  • The URI you need to use would be "https://www.googleapis.com/upload/drive/v3/files?supportsTeamDrives=true&uploadType=resumable".

Sample:

function uploadToSharedDrive(){
  var url = "https://www.googleapis.com/upload/drive/v3/files?supportsTeamDrives=true&uploadType=resumable"; 
  var resumeBlob = Utilities.newBlob('Hire me!');

  var formData = {
    'name': 'Bob Smith',
    'mimeType': 'text/plain',
    'parents': [
      "ID of the shared drive"
    ]
  };
  params = {
    headers: {
      Authorization: 'Bearer ' + service.getAccessToken()   
    },
    contentType:  'application/json',    
    method: 'post',
    payload: JSON.stringify(formData),
  }
  var response = UrlFetchApp.fetch(url, params);
  Logger.log(response.getContentText()); 
  data = resumeBlob.getBytes();
  var params2 = {
    method: "put",
    payload: data,
    muteHttpExceptions: true,
  };
  var location = response.getHeaders().Location;
  var response = UrlFetchApp.fetch(location, params2);
  Logger.log(response.getContentText())  
}


来源:https://stackoverflow.com/questions/61727638/how-to-insert-file-to-a-shared-drive-using-rest-on-apps-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!