直接和續傳的媒體上傳作業
透過集合功能整理內容 你可以依據偏好儲存及分類內容。
本文說明如何搭配使用直接上傳和支援續傳的媒體檔案: 適用於 Java 的 Google API 用戶端程式庫
支援續傳的媒體上傳作業
將大型媒體檔案上傳至伺服器時,請使用支援續傳的媒體檔案進行以下作業: 分批傳送檔案Google API 產生的程式庫包含 以便與支援續傳的媒體上傳作業互動的便利方法。
支援續傳的媒體上傳通訊協定與支援續傳的媒體上傳作業相似 通訊協定 (詳情請參閱 Google Drive API 說明文件) 中所述。
通訊協定設計
以下是支援續傳的媒體上傳通訊協定的運作方式:

實作詳情
主要類別為 MediaHttpUploader 和 MediaHttpProgressListener。
如果服務專屬產生程式庫中的方法包含 mediaUpload
參數加入探索文件中, 反而為這些方法建立方便好用的方法 InputStreamContent 做為參數(如要進一步瞭解如何透過 Google API 使用媒體上傳功能, 探索服務,請參閱 媒體上傳)。
例如 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 版導入媒體上傳功能 適用於 Java 的 Google API 用戶端程式庫版本。
直接上傳媒體會透過一個 HTTP 要求上傳整個檔案,而不是 支援續傳的媒體上傳通訊協定,可透過多個要求上傳檔案。 直接上傳會減少 HTTP 要求的數量,但這麼做會增加 可能發生在 上傳。
直接媒體上傳的使用方式與上述 支援續傳的媒體上傳作業,以及下列向 MediaHttpUploader 的呼叫 只允許直接上傳
mediaHttpUploader.setDirectUploadEnabled(true);
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
上次更新時間:2025-07-26 (世界標準時間)。
[[["容易理解","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-07-26 (世界標準時間)。"],[[["\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,["\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\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\nThe following sequence diagram shows how the resumable media upload protocol works:\n\n\nImplementation details\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\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```"]]