미디어 업로드
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
몇몇 API 메서드는 일반 본문 외에도 미디어 업로드를 지원합니다.
이 경우, 추가 요청을 얻기 위해 일반 요청 메서드가 오버로드됩니다.
업로드하려면 Stream
하세요.
개요
업로드할 Stream
의 경우 재개 가능 옵션을 사용해야 합니다.
미디어 업로드를 사용하면 스트림을 더 작은 단위로 업로드할 수 있습니다.
이 기능은 대용량 파일을 전송하거나
네트워크 중단이나 다른 전송의 가능성에 대해
높은 편이며
또한 네트워크 장애 시 대역폭 사용량을 줄일 수 있습니다.
대용량 파일 업로드를 처음부터 다시 시작할 필요가 없기 때문입니다.
재개 가능한 미디어 업로드는 Google API .NET 클라이언트 라이브러리의 기능이었습니다.
1.2.0-beta부터 지원됩니다.
Google API 고유 라이브러리에는
사용할 수 있습니다.
재개 가능한 미디어 업로드 프로토콜은
Drive API의 미디어 업로드 페이지에서 찾을 수 있습니다.
기본적으로 다룰 주제는
ResumableUpload
이 구현에서는 미디어 콘텐츠가 청크로 업로드됩니다.
기본 청크 크기는 10MB이지만
요청의 ChunkSize
속성을 256KB의 배수로 설정합니다.
요청에 서버 오류가 발생하면 지수 백오프
정책은 업로드되지 않은 바이트를 다시 보내는 데 사용됩니다.
기본적으로 지수 백오프는 각 클라이언트 요청에 대해 사용 설정됩니다.
구성 시 기본 동작을 변경할 수 있습니다.
새 서비스 객체를
<ph type="x-smartling-placeholder"></ph>
BaseClientService.Initializer
의 DefaultExponentialBackOffPolicy
속성
및/또는
<ph type="x-smartling-placeholder"></ph>
HttpClientInitializer
속성을 IConfigurableHttpClientInitializer
의 자체 구현에 추가합니다.
몇 가지 백오프 정책을 추가합니다.
미디어 업로드를 지원하는 방법은
참조 문서에서 확인하세요.
이러한 API 메서드의 경우 편의 Upload
와
UploadAsync
메서드가 추가되었습니다.
이러한 메서드는 Stream
를 사용하여 업로드 및 콘텐츠 유형을 매개변수로 사용합니다.
업로드하는 스트림의 위치가 0인지 확인하세요. 그렇지 않으면 다음과 같은 오류가 발생합니다.
'System.InvalidOperationException: The given header was not found'(지정된 헤더를 찾을 수 없음)가 발생했습니다.
프레임워크의 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");
달리 명시되지 않는 한 이 페이지의 콘텐츠에는 Creative Commons Attribution 4.0 라이선스에 따라 라이선스가 부여되며, 코드 샘플에는 Apache 2.0 라이선스에 따라 라이선스가 부여됩니다. 자세한 내용은 Google Developers 사이트 정책을 참조하세요. 자바는 Oracle 및/또는 Oracle 계열사의 등록 상표입니다.
최종 업데이트: 2025-07-26(UTC)
[null,null,["최종 업데이트: 2025-07-26(UTC)"],[[["\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```"]]