使用 google apps 脚本使用狭窄的 Drive.file 范围将 MS DOCX 文件转换为 Google 文档

问题描述 投票:0回答:1

问题

我正在使用 Google Drive API 和 Google Picker API 将 DOCX 文件转换为 Google Docs 格式。但是,我在使用狭窄的

drive.file
范围进行授权时遇到了问题。具体来说,即使使用 Google Picker 选择文件,我也无法转换文件。

以下是我想要实现的目标的简要概述:

  1. 使用 Google Picker:我使用 Google Picker API 来允许用户从 Google 云端硬盘中选择文件。
  2. Drive API v3:我需要将选定的 DOCX 文件转换为 Google Docs 格式。
  3. 狭窄的 OAuth 范围:我使用
    drive.file
    范围来限制仅访问用户已明确授予我的应用程序访问权限的文件。

问题

尝试将 DOCX 文件转换为 Google 文档时,我收到一条错误消息,指示找不到该文件。这是说明该问题的代码片段:

function convertDocxToGdoc(docxFileId, folderId) {
  try {
    // Prepare the resource object for the converted file
    var resource = {
      name: 'Converted Document', // Title for the converted Google Doc
      mimeType: MimeType.GOOGLE_DOCS,
      parents: [{ id: folderId }] // Parent folder to place the converted file
    };

    // Fetch the DOCX file content using its ID
    var response = UrlFetchApp.fetch('https://drive.google.com/uc?id=' + docxFileId + '&export=download', {
      headers: {
        Authorization: 'Bearer ' + ScriptApp.getOAuthToken()
      }
    });
    var blob = response.getBlob();

    // Use Drive API v3 to create the converted file
    var convertedFile = Drive.Files.create(resource, blob, {
      fields: 'id'
    });

    return convertedFile.id;

  } catch (e) {
    Logger.log('An error occurred during conversion: ' + e.message);
    return null;
  }
}
google-apps-script google-drive-api google-drive-picker
1个回答
0
投票

确保您的 Google Picker API 配置正确处理文件选择并将文件 ID 传递给您的转换。用户应明确授予通过选取器选择的每个文件的权限。

要有效使用 Picker API,特别是在处理 OAuth 范围和文件访问权限时,参考 Google 开发者文档提供的示例会很有帮助。

确保 Picker API 已正确加载并使用必要的 OAuth 范围进行授权。管理选择事件以检索文件 ID 和其他必要的元数据,并使用

drive.file
范围来确保您的应用程序只能访问用户通过选取器选择的文件。

这是一个片段,您可以将其与其余代码集成,以确保调用正确检索文件:

const res = await gapi.client.drive.files.get({
        'fileId': fileId,
        'fields': '*',
      });
      text += Drive API response for first document: \n${JSON.stringify(res.result, null, 2)}\n;
      window.document.getElementById('content').innerText = text;
    }
  }
© www.soinside.com 2019 - 2024. All rights reserved.