Search code examples
javascriptgoogle-drive-apigoogle-apis-explorer

Update file name using Google Drive Rest API


Trying to rename all files in folder, nothing much, just want to add an prefix in all files, using Javascript. Getting error as: "Uncaught TypeError: gapi.client.drive.files.patch is not a function"

listFiles Function is able to fetch the file id and current name, but gapi.client.drive.files.patch throws above error.

Tried with gapi.client.drive.properties.patch but it also gave an error.!

Code:

<button id="authorize-button" style="display: none;">Authorize</button>
<button id="signout-button" style="display: none;">Sign Out</button>
<p id="list" style="display: none;">Enter Folder ID:
<input type="text" id="listInput" size="40" />
<button id="list-button" onClick="listFiles();">Get List</button></p>
<pre id="content"></pre>

<script type="text/javascript">
var CLIENT_ID = '';
var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/drive/v3/rest"];
var SCOPES = 'https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/drive.appdata https://www.googleapis.com/auth/drive.apps.readonly https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/drive.metadata https://www.googleapis.com/auth/drive.scripts';
var authorizeButton = document.getElementById('authorize-button');
var signoutButton = document.getElementById('signout-button');
var pre = document.getElementById('content');
var list = document.getElementById('list');
var listInput = document.getElementById('listInput');
var listButton = document.getElementById('list-button');

function handleClientLoad() {
    gapi.load('client:auth2', initClient);
}
function initClient() {
    gapi.client.init({
        discoveryDocs: DISCOVERY_DOCS,
        clientId: CLIENT_ID,
        scope: SCOPES
    }).then(function () {
        // Listen for sign-in state changes.
        gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
        // Handle the initial sign-in state.
        updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
        authorizeButton.onclick = handleAuthClick;
        signoutButton.onclick = handleSignoutClick;
    });
}
function updateSigninStatus(isSignedIn) {
    if (isSignedIn) {
        authorizeButton.style.display = 'none';
        signoutButton.style.display = 'block';
        list.style.display = 'block';
    } else {
        authorizeButton.style.display = 'block';
        signoutButton.style.display = 'none';
        list.style.display = 'none';
        clearPre();
    }
}
function handleAuthClick(event) {
    gapi.auth2.getAuthInstance().signIn();
}
function handleSignoutClick(event) {
    gapi.auth2.getAuthInstance().signOut();
}
function appendPre(message) {
    var textContent = document.createTextNode(message + '\n');
    pre.appendChild(textContent);
}
function clearPre() {
    pre.innerHTML = "";
}
function listFiles() {
    clearPre();
    appendPre('Getting Files List......');
    gapi.client.drive.files.list({
        'q' : "'" + listInput.value + "' in parents",
        'orderBy' : 'name',
        'pageSize': 1000,
        'fields': "nextPageToken, files(id, name, parents, mimeType)"
    }).then(function(response) {
        clearPre();
        var files = response.result.files;
        console.log(files);
        if (files && files.length > 0) {
            var currentFile;
            var currentFileId;
            appendPre('Count: ' + files.length + ' Files:');
            for (var i = 0; i < files.length; i++) {
                currentFile = files[i].name;
                currentFileId = files[i].id;
                appendPre(currentFile);
                alert(currentFileId + ' Rename ' + currentFile);
                *********Getting Error here*********
                var request = gapi.client.drive.files.patch({
                    'fileId': currentFileId,
                    'resource': {'title': 'Rename ' + currentFile}
                });
                request.execute(function(resp) {
                    console.log('New Title: ' + resp.title);
                });
            }
        } else {
            appendPre('No files found.');
        }
    });
}
</script>
<script async defer src="https://apis.google.com/js/api.js" nload="this.onload=function(){};handleClientLoad()" onreadystatechange="if this.readyState === 'complete') this.onload()">
</script>

Solution

  • I can see in your code that you are using V3.

    gapi.client.drive.files.patch is deprecated in the said version, you can use Files: update instead, to update the desired filenames.

    Or other way around, you can switch to V2 and use the code provided in the documentation.

    /**
     * Rename a file.
     *
     * @param {String} fileId <span style="font-size: 13px; ">ID of the file to rename.</span><br> * @param {String} newTitle New title for the file.
     */
    function renameFile(fileId, newTitle) {
      var body = {'title': newTitle};
      var request = gapi.client.drive.files.patch({
        'fileId': fileId,
        'resource': body
      });
      request.execute(function(resp) {
        console.log('New Title: ' + resp.title);
      });
    }