Change file name of file uploaded using Google Drive API - Apps Script

纵饮孤独 提交于 2021-02-11 15:51:57

问题


I created a script that can upload files on Google Drive Shared Drives using service account. However, I having trouble on renaming the file. I always get "Untitled" file name.

This is my code:

function movefiletoDrive(fileId, driveID, parentDriveId){

  var body = {"title":"RJ"}

  var service = getDriveService();
    service.reset()
      if (service.hasAccess()) {
         var url = 'https://www.googleapis.com/drive/v3/files/'+fileId+'?addParents='+driveID+'&removeParents='+parentDriveId+'&supportsTeamDrives=true';
         var params = {
          headers: {
            Authorization: 'Bearer ' + service.getAccessToken()
          },
          method:'PATCH'
         };

        var response2 = UrlFetchApp.fetch(url, params);
        var response2parse = JSON.parse(response2.getContentText());
        var newFileId = response2parse.id

        //changeFileName(newFileId);
        Logger.log(response2parse);
      }
}

I've tried add the parameter "title" and "name" on the URL to change the file name but no luck.

Any help will be appreciated. Thanks.


回答1:


  1. It is crucial to define the contentType
  2. The correct parameter for the UL fetch is name, not title

A working code could look like this:

function movefiletoDrive(fileId, driveID, parentDriveId){

  var body = {"name":"RJ"}
  var service = getDriveService();
  service.reset()
  if (service.hasAccess()) {
    var url = 'https://www.googleapis.com/drive/v3/files/'+fileId+'?addParents='+driveID+'&removeParents='+parentDriveId+'&supportsTeamDrives=true';
    var params = {
      headers: {
        Authorization: 'Bearer ' + service.getAccessToken()
      },
      method:'patch',
      contentType: 'application/json',
      payload: JSON.stringify(body)
    };    
    var response2 = UrlFetchApp.fetch(url, params);
    var response2parse = JSON.parse(response2.getContentText());
    var newFileId = response2parse.id;
    changeFileName(newFileId);
    Logger.log(response2parse);
  }
}

If you encounter any issue with this solution or the one I provided for your other question - please be so kind to come back to me about this.



来源:https://stackoverflow.com/questions/61797113/change-file-name-of-file-uploaded-using-google-drive-api-apps-script

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