【问题标题】:Update file content on google drive using javascript使用javascript更新谷歌驱动器上的文件内容
【发布时间】:2012-08-10 11:05:45
【问题描述】:

基于@Nvico great answer 我能够将文件上传到谷歌驱动器,问题是答案上的代码每次都会创建一个新文件,有没有办法给已创建的文件 ID 来更新其内容直接(使用Files:update api)而不创建新的?

目前我的解决方案是每次我想更新文件以删除旧文件时​​使用Files:delete api,然后使用@Nvico 代码创建一个新文件

【问题讨论】:

    标签: javascript google-drive-api


    【解决方案1】:

    您可以使用几乎相同的代码向 drive.files.update 端点发送更新请求,而不是使用 drive.files.insert 端点:

    /**
     * Update existing file.
     *
     * @param {String} fileId ID of the file to update.
     * @param {Object} fileMetadata existing Drive file's metadata.
     * @param {File} fileData File object to read data from.
     * @param {Function} callback Callback function to call when the request is complete.
     */
    function updateFile(fileId, fileMetadata, fileData, callback) {
      const boundary = '-------314159265358979323846';
      const delimiter = "\r\n--" + boundary + "\r\n";
      const close_delim = "\r\n--" + boundary + "--";
    
      var reader = new FileReader();
      reader.readAsBinaryString(fileData);
      reader.onload = function(e) {
        var contentType = fileData.type || 'application/octect-stream';
        // Updating the metadata is optional and you can instead use the value from drive.files.get.
        var base64Data = btoa(reader.result);
        var multipartRequestBody =
            delimiter +
            'Content-Type: application/json\r\n\r\n' +
            JSON.stringify(fileMetadata) +
            delimiter +
            'Content-Type: ' + contentType + '\r\n' +
            'Content-Transfer-Encoding: base64\r\n' +
            '\r\n' +
            base64Data +
            close_delim;
    
        var request = gapi.client.request({
            'path': '/upload/drive/v2/files/' + fileId,
            'method': 'PUT',
            'params': {'uploadType': 'multipart', 'alt': 'json'},
            'headers': {
              'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'
            },
            'body': multipartRequestBody});
        if (!callback) {
          callback = function(file) {
            console.log(file)
          };
        }
        request.execute(callback);
      }
    }
    

    主要区别在于请求的URL和方法:

    PUT /upload/drive/v2/files/<FILE_ID>
    

    【讨论】:

    • 感谢它有效,我尝试仅在我自己的原始代码中更改端点,但它不起作用,可能是因为 alt:json 的原因?我不知道这可能是网址中的拼写错误.. 无论如何谢谢:)
    • 您可能忘记将方法从POST 更改为PUTalt=json 查询参数在发送文本内容数据时很有用,让 API 知道 JSON 文档是元数据,另一部分是内容。
    • @Alain - 你能帮忙传递什么 fileData 吗?尝试传递字符串不起作用。它需要哪个对象以及如何获取?
    猜你喜欢
    • 2017-01-29
    • 1970-01-01
    • 2021-07-07
    • 1970-01-01
    • 1970-01-01
    • 2014-08-10
    • 1970-01-01
    • 1970-01-01
    • 2021-08-18
    相关资源
    最近更新 更多