我在上传 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;
}
文件 MIME 类型 https://developers.google.com/drive/v3/web/manage-downloads
或者使用“importFormats”参数。 https://developers.google.com/drive/v3/reference/about/get
我也痛苦了很长一段时间。 为了让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',
]);
这是用 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 似乎对传入的内容非常挑剔。如果我弄清楚的话,将更新此答案以包括