上传媒体
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
除了常规正文之外,一些 API 方法还支持上传媒体内容。
在这种情况下,常规请求方法会过载,以获取额外的
Stream
即可上传。
概览
对于您要上传的任何 Stream
,您都应使用可续传
媒体上传,允许以较小的数据块上传视频流。
如果您要传输大型文件
以及出现网络中断或其他情况
也会很低
还可以减少网络故障时对带宽的占用
因为您不必从头开始重新上传大型文件。
可续传媒体上传是 Google API .NET 客户端库中的一项功能
从 1.2.0-beta 开始。
Google API 特定的库包含
此功能的交互方式。
例如,
Drive API 的媒体上传页面。
感兴趣的主要类是
ResumableUpload
。
在此实现中,媒体内容以数据块的形式上传。
默认数据块大小为 10MB,但您可以通过
将请求中的 ChunkSize
属性设置为 256KB 的任意倍数。
如果请求遇到服务器错误,则使用指数退避算法
政策用于重新发送未成功上传的字节。
默认情况下,系统会为每个客户端请求启用指数退避算法。
您可以在构建
创建新的 Service 对象
<ph type="x-smartling-placeholder"></ph>
BaseClientService.Initializer
上的DefaultExponentialBackOffPolicy
房源
和/或设置
HttpClientInitializer
属性添加到您自己的 IConfigurableHttpClientInitializer
实现中
添加了一些退避政策
明确了支持媒体上传的方法
。
对于这些 API 方法,使用 Upload
和
添加了 UploadAsync
方法。
这些方法接受上传 Stream
及其内容类型作为参数。
请确保您上传的信息流的位置为 0,否则您会收到错误消息,例如
“System.InvalidOperationException:未找到指定的标头”。
请注意,由于框架的 HttpClient
的行为,
类,如果上传超时,则会抛出 TaskCanceledException
。
如果您看到此异常,请考虑手动增加 Timeout
属性,
您的服务对象使用的客户端。
示例代码
// Create the service using the client credentials.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Application_Name"
});
using var uploadStream = System.IO.File.OpenRead("Local_File_Name");
// Create the File resource to upload.
Google.Apis.Drive.v3.Data.File driveFile = new Google.Apis.Drive.v3.Data.File
{
Name = "Drive_File_Name"
};
// Get the media upload request object.
FilesResource.CreateMediaUpload insertRequest = service.Files.Create(
driveFile, uploadStream, "image/jpeg");
// Add handlers which will be notified on progress changes and upload completion.
// Notification of progress changed will be invoked when the upload was started,
// on each upload chunk, and on success or failure.
insertRequest.ProgressChanged += Upload_ProgressChanged;
insertRequest.ResponseReceived += Upload_ResponseReceived;
await insertRequest.UploadAsync();
static void Upload_ProgressChanged(IUploadProgress progress) =>
Console.WriteLine(progress.Status + " " + progress.BytesSent);
static void Upload_ResponseReceived(Google.Apis.Drive.v3.Data.File file) =>
Console.WriteLine(file.Name + " was uploaded successfully");
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-07-26。
[null,null,["最后更新时间 (UTC):2025-07-26。"],[[["\u003cp\u003eSome API methods allow uploading media using resumable media upload, enabling the transfer of large files in smaller chunks, reducing bandwidth usage, and minimizing interruptions.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eResumableUpload\u003c/code\u003e class facilitates resumable media uploads with a default chunk size of 10MB, adjustable to multiples of 256KB, and includes exponential backoff for error handling.\u003c/p\u003e\n"],["\u003cp\u003eConvenience methods \u003ccode\u003eUpload\u003c/code\u003e and \u003ccode\u003eUploadAsync\u003c/code\u003e are available for API methods supporting media upload, accepting a stream and its content type as parameters, ensuring the stream's position is at 0 to avoid errors.\u003c/p\u003e\n"],["\u003cp\u003eConsider increasing the \u003ccode\u003eHttpClient\u003c/code\u003e timeout property to prevent \u003ccode\u003eTaskCanceledException\u003c/code\u003e during prolonged uploads, as demonstrated in the provided sample code.\u003c/p\u003e\n"],["\u003cp\u003eResumable media upload functionality is accessible through the Google API .NET client library, offering detailed documentation and progress tracking capabilities.\u003c/p\u003e\n"]]],[],null,["# Upload Media\n\nSeveral API methods support uploading media in addition to a regular body.\nIn that case, the regular request method is overloaded to get an additional\n`Stream` to upload.\n\nOverview\n--------\n\n\nFor any `Stream` you wish to upload, you should use resumable\nmedia upload, which allows streams to be uploaded in smaller chunks.\nThis is especially useful if you are transferring large files,\nand the likelihood of a network interruption or some other transmission\nfailure is high.\nIt can also reduce your bandwidth usage in the event of network failures\nbecause you don't have to restart large file uploads from the beginning.\n\nResumableMediaUpload\n--------------------\n\n\nResumable Media Upload has been a feature in the Google API .NET client library\nsince 1.2.0-beta.\nThe Google API-specific libraries contain convenience methods for\ninteracting with this feature.\n\n\nThe resumable media upload protocol is described, for example, on the\n[media upload page for the Drive API](https://developers.google.com/drive/manage-uploads#resumable).\nThe main class of interest is\n[`ResumableUpload`](https://googleapis.dev/dotnet/Google.Apis/latest/api/Google.Apis.Upload.ResumableUpload.html).\nIn this implementation, the media content is uploaded in chunks.\n\n\nThe default chunk size is 10MB, but you can change it by\nsetting the `ChunkSize` property on the request to any multiple of 256KB.\nIf a server error is encountered in a request then exponential backoff\npolicy is used to resend the bytes that were not successfully uploaded.\nBy default, exponential backoff is enabled for each client request.\nYou can change the default behavior when you construct\na new service object by changing the\n[`DefaultExponentialBackOffPolicy`](https://googleapis.dev/dotnet/Google.Apis/latest/api/Google.Apis.Services.BaseClientService.Initializer.html#Google_Apis_Services_BaseClientService_Initializer_DefaultExponentialBackOffPolicy) property on `BaseClientService.Initializer`\nand/or setting the\n[`HttpClientInitializer`](https://googleapis.dev/dotnet/Google.Apis/latest/api/Google.Apis.Services.BaseClientService.Initializer.html#Google_Apis_Services_BaseClientService_Initializer_HttpClientInitializer)\nproperty to your own implementation of `IConfigurableHttpClientInitializer`\nthat adds some backoff policy.\n\n\nThe methods that support media upload are identified\nin the reference documentation for the API-specific documentation.\nFor these API methods, convenience `Upload` and\n`UploadAsync` methods are added.\nThose methods take a `Stream` to upload and its content type as parameters.\n\n\nMake sure that the position of the stream you upload is 0, otherwise you will receive an error, such as\n\"System.InvalidOperationException: The given header was not found\".\n\n\nNote that due to the behavior of the framework's `HttpClient`\nclass, if the upload times out, a `TaskCanceledException` is thrown.\nIf you see this exception, consider manually increasing the `Timeout` property in\nthe client used by your service object.\n\nSample Code\n-----------\n\n```gdscript\n// Create the service using the client credentials.\nvar service = new DriveService(new BaseClientService.Initializer()\n{\n HttpClientInitializer = credential,\n ApplicationName = \"Application_Name\"\n});\n\nusing var uploadStream = System.IO.File.OpenRead(\"Local_File_Name\");\n\n// Create the File resource to upload.\nGoogle.Apis.Drive.v3.Data.File driveFile = new Google.Apis.Drive.v3.Data.File\n{\n Name = \"Drive_File_Name\"\n};\n// Get the media upload request object.\nFilesResource.CreateMediaUpload insertRequest = service.Files.Create(\n driveFile, uploadStream, \"image/jpeg\");\n\n// Add handlers which will be notified on progress changes and upload completion.\n// Notification of progress changed will be invoked when the upload was started,\n// on each upload chunk, and on success or failure.\ninsertRequest.ProgressChanged += Upload_ProgressChanged;\ninsertRequest.ResponseReceived += Upload_ResponseReceived;\n\nawait insertRequest.UploadAsync();\n\nstatic void Upload_ProgressChanged(IUploadProgress progress) =\u003e\n Console.WriteLine(progress.Status + \" \" + progress.BytesSent);\n\nstatic void Upload_ResponseReceived(Google.Apis.Drive.v3.Data.File file) =\u003e\n Console.WriteLine(file.Name + \" was uploaded successfully\");\n```"]]