如何上传/转换 *.docx 为 google 文档?谷歌云端硬盘 API v3

Bog*_*ogu 7 c# google-api google-drive-api google-api-dotnet-client

我在上传 microsoft/libre Office 文档以通过 Google Apps 进行编辑时遇到问题。对于电子表格,它可以正常工作,但对于文档则不然。

当我上传扩展名为 *.odt、*.docx 的文件时,我可以通过 Google 云端硬盘上的 google 查看器查看内容,但是当我单击文档顶部的“使用按钮进行编辑”时,Google 云端硬盘会创建一个具有相同内容和名称的新文件但我没有关于描述中的原始文件 ID 或任何能力的信息。有什么想法如何上传准备在线编辑的文档吗?

  private async Task<string> UploadFileToGoogleDrive(string filePath, GoogleDriveFile file)
    {
        var fileData = new Google.Apis.Drive.v3.Data.File()
        {
            Name = file.Name,
            MimeType = file.MimeType

        };
        if (!String.IsNullOrEmpty(file.ParentId))
            fileData.Parents = new List<string>() { file.ParentId };

        FilesResource.CreateMediaUpload request;

        using (var stream = new FileStream(filePath, FileMode.Open))
        {
             request = _driveService.Files.Create(fileData, stream, StringEnum.GetStringValue(file.FileContent));
             request.Fields = "id";

             var uploadProgress = await request.UploadAsync();
             if (uploadProgress.Exception != null)
                 throw uploadProgress.Exception; 
        }
        return request.ResponseBody.Id;
    }
Run Code Online (Sandbox Code Playgroud)

文件 mime 类型 https://developers.google.com/drive/v3/web/manage-downloads

或者使用“importFormats”参数。 https://developers.google.com/drive/v3/reference/about/get

小智 8

我也痛苦了很长一段时间。为了让Google转换为我们需要的格式,我们在元数据的MimeType中指定它。您还需要在内容对象的 MimeType 中指定当前文件格式。

仅在 PHP 上有一个示例

$fileMetadata = new \Google_Service_Drive_DriveFile([
    'name' => $this->_fileName,
    'parents' => array($directoryId),
    'mimeType' => 'application/vnd.google-apps.document'
]);

return $this->_service()->files->create($fileMetadata, [
    'data' => $document,
    'mimeType' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'uploadType' => 'multipart',
    'fields' => 'id',
]);
Run Code Online (Sandbox Code Playgroud)