Обновите имя файла с помощью Google Drive Rest API

Пытаюсь переименовать все файлы в папке, ничего особенного, просто хочу добавить префикс во все файлы, используя Javascript. Получение ошибки: «Uncaught TypeError: gapi.client.drive.files.patch не является функцией»

Функция listFiles может получить идентификатор файла и текущее имя, но gapi.client.drive.files.patch выдает указанную выше ошибку.

Пробовал с gapi.client.drive.properties.patch но тоже выдало ошибку.!

Код:

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

person Shripal Gandhi    schedule 19.08.2017    source источник


Ответы (3)


Я вижу в вашем коде, что вы используете V3.

gapi.client.drive.files.patch в указанной версии устарел, вы можете использовать Файлы: обновить вместо этого обновить нужные имена файлов.

Или наоборот, вы можете переключиться на версию 2 и использовать код, указанный в документация.

/**
 * 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);
  });
}
person MαπμQμαπkγVπ.0    schedule 20.08.2017
comment
Спасибо. Я не знал, что это было deprication.! - person Shripal Gandhi; 21.03.2018

Оцените, что исходный вопрос был Javascript и V2 API Google Диска...

Пытаясь использовать Python и V3, мне потребовалось некоторое время, чтобы понять, как это сделать. Мне не хватало аргумента ключевого слова body={}, который вам нужен для отправки свойства name.

Предполагая, что вы уже получили file_id, которое хотите переименовать, в отдельном вызове, например:

drive.files().update(
       fileId=file_id,
       supportsAllDrives='true',
       body={'name': 'new name for this file'}
       ).execute()
person James Leedham    schedule 25.08.2020

После 3 попыток использовать чужие модули NPM для Google Диска, я решил, что пришло время сделать свой собственный, и я ПРОСТО добавлял функциональность mv(), поэтому у меня был этот бой, и вот что я придумал и использовал в своей библиотеке. Сегодня она не публикуется и имена будут меняться, но если кто-то хочет попробовать бета-версию, напишите мне в твиттере под тем же именем.

примечание: вам нужны только addParents и removeParents, если вы «перемещаете» файл, и вам нужно только имя, если вы действительно собираетесь его переименовывать.

drive.files.update({
            fileId: driveFileId,
            addParents: commaStringOfParents,
            removeParents: commaStringOfParents,
            resource: { name: newFileName }
        }, (err, res) => {
            if (err) handleError(err);
            let files = res.data
            // Do stuff here
        }
person rainabba    schedule 25.05.2018