미디어 업로드

여러 API 메서드는 일반 본문 외에 미디어 업로드를 지원합니다. 이 경우 일반 요청 메서드가 과부하되어 업로드할 추가 Stream을 가져옵니다.

개요

업로드하려는 모든 Stream에는 스트림을 더 작은 단위로 업로드할 수 있는 재개 가능한 미디어 업로드를 사용해야 합니다. 대용량 파일을 전송하거나 네트워크 중단 또는 기타 전송 실패가 발생할 가능성이 높은 경우에 특히 유용합니다. 또한 대용량 파일을 처음부터 다시 업로드할 필요가 없으므로 네트워크 장애 발생 시 대역폭 사용량도 줄일 수 있습니다.

ResumableMediaUpload

재개 가능한 미디어 업로드는 1 .2.0-beta부터 Google API.NET 클라이언트 라이브러리의 기능이었습니다. Google API 관련 라이브러리에는 이 기능과 상호작용하기 위한 편의 메서드가 포함되어 있습니다.

재개 가능한 미디어 업로드 프로토콜은 예를 들어 Drive API의 미디어 업로드 페이지에 설명되어 있습니다. 관심 있는 기본 클래스는 ResumableUpload입니다. 이 구현에서는 미디어 콘텐츠를 단위별로 업로드합니다.

기본 단위 크기는 10MB이지만 요청의 ChunkSize 속성을 256KB의 배수로 설정하여 변경할 수 있습니다. 요청에 서버 오류가 발생하면 지수 백오프 정책을 사용하여 성공적으로 업로드되지 않은 바이트를 다시 전송합니다. 기본적으로 지수 백오프는 각 클라이언트 요청에 대해 사용 설정됩니다. 새 서비스 객체를 구성할 때 BaseClientService.Initializer DefaultExponentialBackOffPolicy 속성을 변경하거나 일부 백오프 정책을 추가하는 자체 IConfigurableHttpClientInitializer 구현으로 HttpClientInitializer 속성을 설정하여 기본 동작을 변경할 수 있습니다.

미디어 업로드를 지원하는 메서드는 API 관련 문서의 참조 문서에 설명되어 있습니다. 이러한 API 메서드에는 편의 UploadUploadAsync 메서드가 추가됩니다. 이러한 메서드는 업로드할 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");