직접 및 재개 가능한 미디어 업로드
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
이 문서에서는 직접 및 재개 가능한 미디어 업로드를 사용하는 방법을 설명합니다.
API 클라이언트 라이브러리를 제공합니다.
재개 가능한 미디어 업로드
대용량 미디어 파일을 서버에 업로드할 때 재개 가능한 미디어 업로드를 사용하면
청크별로 파일 청크를 보냅니다. Google API 생성 라이브러리에는
재개 가능한 미디어 업로드와 상호작용하기 위한 편리한 메서드를 제공합니다.
재개 가능한 미디어 업로드 프로토콜은 재개 가능한 미디어 업로드와 유사합니다.
Google Drive API 문서에 설명된 대로 프로토콜을 사용해야 합니다.
프로토콜 설계
다음 시퀀스 다이어그램은 재개 가능한 미디어 업로드 프로토콜의 작동 방식을 보여줍니다.

구현 세부정보
주요 관심 클래스는
MediaHttpUploader
MediaHttpProgressListener가 있습니다.
서비스별로 생성된 라이브러리의 메서드에 mediaUpload
이 포함된 경우
매개변수(검색 문서)가 포함되어 있습니다.
그러면 이러한 메서드를 위한 편의 메서드가 생성되어
InputStreamContent
를 매개변수로 사용합니다. (Google API를 통한 미디어 업로드 사용에 대한 자세한 내용은
Discovery Service의 경우
미디어 업로드)
예: Drive API의 insert
메서드
mediaUpload
를 지원하며 다음 코드를 사용하여 파일을 업로드할 수 있습니다.
class CustomProgressListener implements MediaHttpUploaderProgressListener {
public void progressChanged(MediaHttpUploader uploader) throws IOException {
switch (uploader.getUploadState()) {
case INITIATION_STARTED:
System.out.println("Initiation has started!");
break;
case INITIATION_COMPLETE:
System.out.println("Initiation is complete!");
break;
case MEDIA_IN_PROGRESS:
System.out.println(uploader.getProgress());
break;
case MEDIA_COMPLETE:
System.out.println("Upload is complete!");
}
}
}
File mediaFile = new File("/tmp/driveFile.jpg");
InputStreamContent mediaContent =
new InputStreamContent("image/jpeg",
new BufferedInputStream(new FileInputStream(mediaFile)));
mediaContent.setLength(mediaFile.length());
Drive.Files.Insert request = drive.files().insert(fileMetadata, mediaContent);
request.getMediaHttpUploader().setProgressListener(new CustomProgressListener());
request.execute();
또한 서비스별
생성됩니다 예를 들면 다음과 같습니다.
File mediaFile = new File("/tmp/Test.jpg");
InputStreamContent mediaContent =
new InputStreamContent("image/jpeg",
new BufferedInputStream(new FileInputStream(mediaFile)));
mediaContent.setLength(mediaFile.length());
MediaHttpUploader uploader = new MediaHttpUploader(mediaContent, transport, httpRequestInitializer);
uploader.setProgressListener(new CustomProgressListener());
HttpResponse response = uploader.upload(requestUrl);
if (!response.isSuccessStatusCode()) {
throw GoogleJsonResponseException(jsonFactory, response);
}
직접 미디어 업로드
재개 가능한 미디어 업로드는 기본적으로 사용 설정되어 있지만 사용 중지하고
대신 미디어 직접 업로드를 사용합니다(예: 작은 파일을 업로드하는 경우). 직접
미디어 업로드는 1.9.0-beta에서 도입되었습니다.
Google API 클라이언트 라이브러리 버전입니다.
직접 미디어 업로드는
여러 요청으로 파일을 업로드하는 재개 가능한 미디어 업로드 프로토콜입니다.
직접 업로드를 수행하면 HTTP 요청 수는 감소하지만
장애 (예: 연결 장애)가 발생할 가능성을
합니다.
직접 미디어 업로드의 사용은 위에서 설명한 것과 동일합니다.
재개 가능한 미디어 업로드 및 MediaHttpUploader를 알려주는 다음 호출
직접 업로드만 할 수 있습니다.
mediaHttpUploader.setDirectUploadEnabled(true);
달리 명시되지 않는 한 이 페이지의 콘텐츠에는 Creative Commons Attribution 4.0 라이선스에 따라 라이선스가 부여되며, 코드 샘플에는 Apache 2.0 라이선스에 따라 라이선스가 부여됩니다. 자세한 내용은 Google Developers 사이트 정책을 참조하세요. 자바는 Oracle 및/또는 Oracle 계열사의 등록 상표입니다.
최종 업데이트: 2025-08-31(UTC)
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["필요한 정보가 없음","missingTheInformationINeed","thumb-down"],["너무 복잡함/단계 수가 너무 많음","tooComplicatedTooManySteps","thumb-down"],["오래됨","outOfDate","thumb-down"],["번역 문제","translationIssue","thumb-down"],["샘플/코드 문제","samplesCodeIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-08-31(UTC)"],[[["\u003cp\u003eThis document explains how to upload media to Google APIs using the Java Client Library, focusing on resumable and direct upload methods.\u003c/p\u003e\n"],["\u003cp\u003eResumable media upload is recommended for large files, allowing uploads in chunks and offering better resilience to network interruptions, similar to Google Drive's approach.\u003c/p\u003e\n"],["\u003cp\u003eDirect media upload sends the entire file in a single request, suitable for smaller files but with a higher risk of failure for larger ones.\u003c/p\u003e\n"],["\u003cp\u003eThe Java Client Library provides \u003ccode\u003eMediaHttpUploader\u003c/code\u003e and \u003ccode\u003eMediaHttpProgressListener\u003c/code\u003e for managing uploads, with built-in support for resumable uploads and an option to enable direct uploads.\u003c/p\u003e\n"],["\u003cp\u003eCode samples demonstrate how to use both resumable and direct uploads with the library, including progress tracking and handling potential errors.\u003c/p\u003e\n"]]],[],null,["# Direct and Resumable Media Uploads\n\n\u003cbr /\u003e\n\nThis document describes how to use direct and resumable media uploads with\nthe Google API Client Library for Java.\n\n\u003cbr /\u003e\n\nResumable media upload\n----------------------\n\nWhen you upload a large media file to a server, use *resumable media upload* to\nsend the file chunk by chunk. The Google API generated libraries contain\nconvenience methods for interacting with resumable media upload.\n\nThe resumable media upload protocol is similar to the resumable media upload\nprotocol described in the [Google Drive API documentation](https://developers.google.com/drive/web/manage-uploads#resumable).\n\nProtocol design\n---------------\n\nThe following sequence diagram shows how the resumable media upload protocol works:\n\n\nImplementation details\n----------------------\n\nThe main classes of interest are\n[MediaHttpUploader](https://googleapis.dev/java/google-api-client/latest/com/google/api/client/googleapis/media/MediaHttpUploader.html)\nand [MediaHttpProgressListener](https://googleapis.dev/java/google-api-client/latest/com/google/api/client/googleapis/media/MediaHttpUploaderProgressListener.html).\n\nIf methods in the service-specific generated libraries contain the `mediaUpload`\nparameter in the [Discovery document](https://developers.google.com/discovery/v1/using),\nthen a convenience method is created for these methods that takes an\n[InputStreamContent](https://googleapis.dev/java/google-http-client/latest/com/google/api/client/http/InputStreamContent.html)\nas a parameter. (For more about using media upload with the Google APIs\nDiscovery Service, see\n[Media upload](https://developers.google.com/discovery/v1/using#discovery-doc-methods-mediaupload).)\n\nFor example, the `insert` method of the [Drive API](https://developers.google.com/drive/api/v2/reference)\nsupports `mediaUpload`, and you can use the following code to upload a file: \n\n```java\nclass CustomProgressListener implements MediaHttpUploaderProgressListener {\n public void progressChanged(MediaHttpUploader uploader) throws IOException {\n switch (uploader.getUploadState()) {\n case INITIATION_STARTED:\n System.out.println(\"Initiation has started!\");\n break;\n case INITIATION_COMPLETE:\n System.out.println(\"Initiation is complete!\");\n break;\n case MEDIA_IN_PROGRESS:\n System.out.println(uploader.getProgress());\n break;\n case MEDIA_COMPLETE:\n System.out.println(\"Upload is complete!\");\n }\n }\n}\n\nFile mediaFile = new File(\"/tmp/driveFile.jpg\");\nInputStreamContent mediaContent =\n new InputStreamContent(\"image/jpeg\",\n new BufferedInputStream(new FileInputStream(mediaFile)));\nmediaContent.setLength(mediaFile.length());\n\nDrive.Files.Insert request = drive.files().insert(fileMetadata, mediaContent);\nrequest.getMediaHttpUploader().setProgressListener(new CustomProgressListener());\nrequest.execute();\n```\n\nYou can also use the resumable media upload feature without the service-specific\ngenerated libraries. Here is an example: \n\n```java\nFile mediaFile = new File(\"/tmp/Test.jpg\");\nInputStreamContent mediaContent =\n new InputStreamContent(\"image/jpeg\",\n new BufferedInputStream(new FileInputStream(mediaFile)));\nmediaContent.setLength(mediaFile.length());\n\nMediaHttpUploader uploader = new MediaHttpUploader(mediaContent, transport, httpRequestInitializer);\nuploader.setProgressListener(new CustomProgressListener());\nHttpResponse response = uploader.upload(requestUrl);\nif (!response.isSuccessStatusCode()) {\n throw GoogleJsonResponseException(jsonFactory, response);\n}\n```\n\n\u003cbr /\u003e\n\nDirect media upload\n-------------------\n\nResumable media upload is enabled by default, but you can disable it and use\ndirect media upload instead, for example if you are uploading a small file. Direct\nmedia upload was introduced in the [1.9.0-beta](http://google-api-java-client.blogspot.com/2012/05/version-190-beta-released.html)\nversion of the Google API Client Library for Java.\n\nDirect media upload uploads the whole file in one HTTP request, as opposed to\nthe resumable media upload protocol, which uploads the file in multiple requests.\nDoing a direct upload reduces the number of HTTP requests but increases the\nchance of failures (such as connection failures) that can happen with large\nuploads.\n\nThe usage for direct media upload is the same as what is described above for\nresumable media upload, plus the following call that tells [MediaHttpUploader](https://googleapis.dev/java/google-api-client/latest/com/google/api/client/googleapis/media/MediaHttpUploader.html)\nto only do direct uploads: \n\n```java\nmediaHttpUploader.setDirectUploadEnabled(true);\n```"]]