使用 Google Drive Rest API 更新文件名

Update file name using Google Drive Rest API

尝试重命名文件夹中的所有文件,没什么,只是想在所有文件中添加一个前缀,使用 Javascript。获取错误为:"Uncaught TypeError: gapi.client.drive.files.patch is not a function"

listFiles 函数能够获取文件 ID 和当前名称,但 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>

我在您的代码中看到您使用的是 V3。

gapi.client.drive.files.patch 在上述版本中已弃用,您可以使用 Files: update 来更新所需的文件名。

或者反过来,您可以切换到 V2 并使用 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);
  });
}

在 3 次尝试将其他人的 NPM 模块用于 Google Drive 之后,我决定是时候自己动手了,我只是添加了 mv() 功能,所以我进行了这场斗争,这就是我的结果了解并在我的图书馆中使用。今天不是 public 并且会更改名称,但如果有人想试用测试版,请在 Twitter 上用相同的名称联系我。

注: 如果你是一个文件,你只需要 addParents 和 removeParents "moving" 并且你只需要 name 如果你真的要重命名它。

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
        }

感谢原始问题 Javascript 和 Google 驱动器的 V2 API...

尝试使用 Python 和 V3,我花了一段时间才弄清楚如何做到这一点。我缺少的一点是 body={} 关键字参数,您需要提交 name 属性.

假设您已经获得 file_id 您想要在单独的调用中重命名,如下所示:

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