gpt4 book ai didi

c# - Google Drive API 上传格式无效?

转载 作者:行者123 更新时间:2023-11-30 17:25:43 25 4
gpt4 key购买 nike

我一直在使用以下方法将图片上传到 Google 云端硬盘:

    public string AddFile(string path, string contentType, string driveId)
{
FilesResource.CreateMediaUpload request;
using (FileStream stream = new FileStream(path,
FileMode.Open))
{
Google.Apis.Drive.v3.Data.File fileMetadata = new Google.Apis.Drive.v3.Data.File
{
Name = Path.GetFileName(path),
DriveId = driveId
};
request = _service.Files.Create(
fileMetadata, stream, contentType);
request.Fields = "id";
request.SupportsTeamDrives = true;
}
IUploadProgress requestResult = request.Upload();
if (requestResult.Exception != null) throw requestResult.Exception;
Google.Apis.Drive.v3.Data.File file = request.ResponseBody;
return file == null ? "" : file.Id;
}

使用 API 客户端库版本 1.40.3.1694,直到今天它都运行良好。现在我在 requestResult.Exception 中遇到这种错误:

System.FormatException: The format of value 'bytes 0--1/660915' is invalid.

我上传的文件只是一个小的 GIF 测试文件,在这种情况下会立即删除。

我是否漏掉了一些明显的东西?

最佳答案

我明白了:

  • 为什么原始代码被破坏了
  • 为什么使用 MemoryStream 修复它
  • 如何更简单地修复它

我还不明白:

  • 您看到的确切错误(我将单独深入研究;我已经为此提交了一个 issue)
  • 你的代码是如何实际工作的

问题是您正在打开一个 FileStream,创建一个请求但不执行它,处理 FileStream然后 执行请求。在您的 MemoryStream 版本中,您不会在上传完成之前处理流。

创建初始请求实际上并不从流中读取数据——它只是准备一些东西。在 Upload 完成之前,您需要保持流打开。因此,您需要做的就是使 using 语句变大:

public string AddFile(string path, string contentType, string driveId)
{
using (FileStream stream = new FileStream(path, FileMode.Open))
{
Google.Apis.Drive.v3.Data.File fileMetadata = new Google.Apis.Drive.v3.Data.File
{
Name = Path.GetFileName(path),
DriveId = driveId
};
var request = _service.Files.Create(fileMetadata, stream, contentType);
request.Fields = "id";
request.SupportsTeamDrives = true;
IUploadProgress requestResult = request.Upload();
if (requestResult.Exception != null) throw requestResult.Exception;
Google.Apis.Drive.v3.Data.File file = request.ResponseBody;
return file == null ? "" : file.Id;
}
}

关于c# - Google Drive API 上传格式无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57796896/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com