本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
您可以使用接聽程式介面追蹤物件上傳至 Amazon S3 的進度。高階分段上傳 API 提供這類接聽程式介面,稱為 ProgressListener
。進度事件定期發生,並會通知接聽程式已傳輸的位元組數。如需更多分段上傳的一般資訊,請參閱在 Amazon S3 中使用分段上傳來上傳和複製物件。
如需搭配額外檢查總和使用分段上傳來上傳物件的端對端程序,請參閱教學課程:透過分段上傳來上傳物件並驗證其資料完整性。
下一節說明如何使用 AWS SDKs 追蹤分段上傳。
TransferManager tm = new TransferManager(new ProfileCredentialsProvider());
PutObjectRequest request = new PutObjectRequest(
existingBucketName, keyName, new File(filePath));
// Subscribe to the event and provide event handler.
request.setProgressListener(new ProgressListener() {
public void progressChanged(ProgressEvent event) {
System.out.println("Transferred bytes: " +
event.getBytesTransfered());
}
});
範例
下列 Java 程式碼會上傳檔案,並使用 ProgressListener
追蹤上傳進度。如需如何建立和測試工作範例的說明,請參閱《 AWS SDK for Java 開發人員指南》中的入門。
import java.io.File;
import com.amazonaws.AmazonClientException;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.event.ProgressEvent;
import com.amazonaws.event.ProgressListener;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.transfer.TransferManager;
import com.amazonaws.services.s3.transfer.Upload;
public class TrackMPUProgressUsingHighLevelAPI {
public static void main(String[] args) throws Exception {
String existingBucketName = "*** Provide bucket name ***";
String keyName = "*** Provide object key ***";
String filePath = "*** file to upload ***";
TransferManager tm = new TransferManager(new ProfileCredentialsProvider());
// For more advanced uploads, you can create a request object
// and supply additional request parameters (ex: progress listeners,
// canned ACLs, etc.)
PutObjectRequest request = new PutObjectRequest(
existingBucketName, keyName, new File(filePath));
// You can ask the upload for its progress, or you can
// add a ProgressListener to your request to receive notifications
// when bytes are transferred.
request.setGeneralProgressListener(new ProgressListener() {
@Override
public void progressChanged(ProgressEvent progressEvent) {
System.out.println("Transferred bytes: " +
progressEvent.getBytesTransferred());
}
});
// TransferManager processes all transfers asynchronously,
// so this call will return immediately.
Upload upload = tm.upload(request);
try {
// You can block and wait for the upload to finish
upload.waitForCompletion();
} catch (AmazonClientException amazonClientException) {
System.out.println("Unable to upload file, upload aborted.");
amazonClientException.printStackTrace();
}
}
}