如何上传/转换* .docx到谷歌文件? Google Drive Api v3

时间:2018-01-17 11:46:01

标签: c# google-api google-drive-api google-api-dotnet-client

我上传微软/ libre office文档以通过谷歌应用程序进行编辑时遇到问题。对于电子表格,它正常工作但对于文档则不然。

当我上传扩展名为* .odt,* .docx的文件时,我可以通过谷歌浏览器上的谷歌浏览器查看内容,但当我点击文档顶部的按钮进行编辑时,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;
    }

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

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

2 个答案:

答案 0 :(得分:1)

我也遭受了很长时间的痛苦。 为了让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',
    ]);

答案 1 :(得分:0)

这里是C#语言(我遵循https://developers.google.com/drive/api/v3/manage-uploads#import_to_google_docs_types_中的这个示例

您应该能够将代码放入文件流的using语句中

    using File = Google.Apis.Drive.v3.Data.File; // This obviously goes at the top of the file, alternatively you can fully qualify the File constructor, although I had ambiguity issued due to also `using System.IO` and the compiler not knowing which `File` I meant specifically. 

    ...

    var fileMetadata = new File() // please note this is Google.Apis.Drive.v3.Data.File;
    {
        Name = "New File Name I Want"
        MimeType = "application/vnd.google-apps.document"
    };

    var request = service.Files.Create(
        fileMetadata, 
        stream, 
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document" // please note this is the mimeType of the source file not the tartget
    ); 
    request.Fields = "id";
    var result = await request.UploadAsync();

根据文档,可以使用“更新”操作而不是“上载”来执行此操作,但这将转换原始文件,并且原始文件将丢失。不幸的是,没有给出有关如何执行此操作的示例,并且API似乎对传入的内容非常挑剔。如果我知道,将更新此答案以包含