Object Storage Service (OSS) は、マルチパートアップロード機能を提供します。 マルチパートアップロードを使用すると、大きなオブジェクトを複数のパートに分割してアップロードできます。 これらのパーツがアップロードされたら、CompleteMultipartUpload操作を呼び出して、パーツを完全なオブジェクトに結合できます。
使用上の注意
このトピックでは、マルチパートアップロードを実行してローカルファイルをアップロードする方法について説明します。 マルチパートアップロードを実行してネットワークまたはデータストリームをアップロードする方法の詳細については、「OSS SDK for Javaを使用してデータストリームを部分的にアップロードするにはどうすればよいですか?」をご参照ください。
このトピックでは、中国 (杭州) リージョンのパブリックエンドポイントを使用します。 OSSと同じリージョンにある他のAlibaba CloudサービスからOSSにアクセスする場合は、内部エンドポイントを使用します。 OSSリージョンとエンドポイントの詳細については、「リージョン、エンドポイント、オープンポート」をご参照ください。
このトピックでは、アクセス資格情報は環境変数から取得します。 アクセス資格情報の設定方法の詳細については、「アクセス資格情報の設定」をご参照ください。
このトピックでは、OSSエンドポイントを使用してOSSClientインスタンスを作成します。 カスタムドメイン名またはSecurity Token Service (STS) を使用してOSSClientインスタンスを作成する場合は、「OSSClientインスタンスの作成」をご参照ください。
マルチパートアップロードを実行するには、
oss:PutObject
権限が必要です。 詳細については、「RAMユーザーへのカスタムポリシーのアタッチ」をご参照ください。
手順
マルチパートアップロードを使用してローカルファイルをアップロードするには、次の手順を実行します。
マルチパートアップロードタスクを開始します。
ossClient.initiateMultipartUploadメソッドを呼び出して、OSSで一意のアップロードIDを取得します。
パーツをアップロード
ossClient.uploadPartメソッドを呼び出して、パーツをアップロードします。
説明マルチパートアップロードタスクでは、部品番号を使用して、オブジェクト内の部品の相対位置を識別します。 既存の部品と同じ部品番号を持つ部品をアップロードすると、既存の部品はアップロードされた部品によって上書きされます。
OSSは、レスポンスのETagヘッダーにアップロードされた各パーツのMD5ハッシュを含めます。
OSSはアップロードされたパーツのMD5ハッシュを計算し、そのMD5ハッシュをOSS SDK for Javaによって計算されたMD5ハッシュと比較します。 2つのハッシュが異なる場合、OSSはInvalidDigestエラーコードを返します。
マルチパートアップロードタスクを完了します。
すべてのパーツがアップロードされたら、e ossClient.com pleteMultipartUploadメソッドを呼び出して、これらのパーツを完全なオブジェクトに結合します。
マルチパートアップロードとマルチパートアップロードを実行できるシナリオの詳細については、「マルチパートアップロード」をご参照ください。
例
次のサンプルコードは、マルチパートアップロードプロセスに従ってマルチパートアップロードタスクを実装する方法の例を示しています。
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.internal.Mimetypes;
import com.aliyun.oss.model.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class Demo {
public static void main(String[] args) throws Exception {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path of the object.
String objectName = "exampledir/exampleobject.txt";
// Specify the full path of the local file that you want to upload.
String filePath = "D:\\localpath\\examplefile.txt";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Create an InitiateMultipartUploadRequest object.
InitiateMultipartUploadRequest request = new InitiateMultipartUploadRequest(bucketName, objectName);
// The following sample code provides an example on how to specify the request headers when you initiate a multipart upload task:
ObjectMetadata metadata = new ObjectMetadata();
// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
// Specify the caching behavior of the web page for the object.
// metadata.setCacheControl("no-cache");
// Specify the name of the downloaded object.
// metadata.setContentDisposition("attachment;filename=oss_MultipartUpload.txt");
// Specify the content encoding format of the object.
// metadata.setContentEncoding(OSSConstants.DEFAULT_CHARSET_NAME);
// Specify whether existing objects are overwritten by objects that have the same names when the multipart upload task is initiated. In this example, this parameter is set to true, which indicates that existing objects cannot be overwritten by objects with the same names.
// metadata.setHeader("x-oss-forbid-overwrite", "true");
// Specify the server-side encryption method that you want to use to encrypt each part of the object that you want to upload.
// metadata.setHeader(OSSHeaders.OSS_SERVER_SIDE_ENCRYPTION, ObjectMetadata.KMS_SERVER_SIDE_ENCRYPTION);
// Specify the algorithm that you want to use to encrypt the object. If you do not specify this parameter, the object is encrypted by using AES-256.
// metadata.setHeader(OSSHeaders.OSS_SERVER_SIDE_DATA_ENCRYPTION, ObjectMetadata.KMS_SERVER_SIDE_ENCRYPTION);
// Specify the ID of the customer master key (CMK) that is managed by Key Management Service (KMS).
// metadata.setHeader(OSSHeaders.OSS_SERVER_SIDE_ENCRYPTION_KEY_ID, "9468da86-3509-4f8d-a61e-6eab1eac****");
// Specify the storage class of the object.
// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard);
// Specify one or more tags for the object.
// metadata.setHeader(OSSHeaders.OSS_TAGGING, "a:1");
// request.setObjectMetadata(metadata);
// Specify ContentType based on the object type. If you do not specify this parameter, the default value of ContentType is used, which is application/oct-srream.
if (metadata.getContentType() == null) {
metadata.setContentType(Mimetypes.getInstance().getMimetype(new File(filePath), objectName));
}
// Initiate the multipart upload task.
InitiateMultipartUploadResult upresult = ossClient.initiateMultipartUpload(request);
// Obtain the upload ID.
String uploadId = upresult.getUploadId();
// Cancel the multipart upload task or list uploaded parts based on the upload ID.
// If you want to cancel a multipart upload task based on the upload ID, obtain the upload ID after you call the InitiateMultipartUpload operation to initiate the multipart upload task.
// If you want to list the uploaded parts in a multipart upload task based on the upload ID, obtain the upload ID after you call the InitiateMultipartUpload operation to initiate the multipart upload task but before you call the CompleteMultipartUpload operation to complete the multipart upload task.
// System.out.println(uploadId);
// partETags is a set of PartETags. A PartETag consists of the part number and ETag of an uploaded part.
List<PartETag> partETags = new ArrayList<PartETag>();
// Specify the size of each part, which is used to calculate the number of parts of the object. Unit: bytes.
final long partSize = 1 * 1024 * 1024L; // Set the part size to 1 MB.
// Calculate the number of parts based on the size of the uploaded data. In the following sample code, a local file is used as an example to describe how to use the File.length() method to obtain the size of the uploaded data.
final File sampleFile = new File(filePath);
long fileLength = sampleFile.length();
int partCount = (int) (fileLength / partSize);
if (fileLength % partSize != 0) {
partCount++;
}
// Upload all parts.
for (int i = 0; i < partCount; i++) {
long startPos = i * partSize;
long curPartSize = (i + 1 == partCount) ? (fileLength - startPos) : partSize;
UploadPartRequest uploadPartRequest = new UploadPartRequest();
uploadPartRequest.setBucketName(bucketName);
uploadPartRequest.setKey(objectName);
uploadPartRequest.setUploadId(uploadId);
// Specify the input stream of the multipart upload task.
// In the following sample code, a local file is used as an example to describe how to create a FIleInputstream and use the InputStream.skip() method to skip the specified data.
InputStream instream = new FileInputStream(sampleFile);
instream.skip(startPos);
uploadPartRequest.setInputStream(instream);
// Specify the part size. The size of each part except for the last part must be greater than or equal to 100 KB.
uploadPartRequest.setPartSize(curPartSize);
// Specify part numbers. Each part has a part number that ranges from 1 to 10,000. If the part number that you specify does not fall within the specified range, OSS returns the InvalidArgument error code.
uploadPartRequest.setPartNumber( i + 1);
// Parts are not necessarily uploaded in order and can be uploaded from different OSS clients. OSS sorts the parts based on the part numbers and combines the parts into a complete object.
UploadPartResult uploadPartResult = ossClient.uploadPart(uploadPartRequest);
// Each time a part is uploaded, OSS returns a result that contains the PartETag of the part. The PartETag is stored in partETags.
partETags.add(uploadPartResult.getPartETag());
}
// Create a CompleteMultipartUploadRequest object.
// When you call the CompleteMultipartUpload operation, you must provide all valid PartETags. After OSS receives the PartETags, OSS verifies all parts one by one. After all parts are verified, OSS combines these parts into a complete object.
CompleteMultipartUploadRequest completeMultipartUploadRequest =
new CompleteMultipartUploadRequest(bucketName, objectName, uploadId, partETags);
// The following sample code provides an example on how to configure the access control list (ACL) of the object when you initiate a multipart upload task:
// completeMultipartUploadRequest.setObjectACL(CannedAccessControlList.Private);
// Specify whether to list all parts that are uploaded by using the current upload ID. For OSS SDK for Java 3.14.0 and later, you can set PartETags in CompleteMultipartUploadRequest to null only when you list all parts uploaded to the OSS server to combine the parts into a complete object.
// Map<String, String> headers = new HashMap<String, String>();
// If you set x-oss-complete-all to yes in the request, OSS lists all parts that are uploaded by using the current upload ID, sorts the parts by part number, and then performs the CompleteMultipartUpload operation.
// If you set x-oss-complete-all to yes in the request, the request body cannot be specified. If you specify the request body, an error is reported.
// headers.put("x-oss-complete-all","yes");
// completeMultipartUploadRequest.setHeaders(headers);
// Complete the multipart upload task.
CompleteMultipartUploadResult completeMultipartUploadResult = ossClient.completeMultipartUpload(completeMultipartUploadRequest);
System.out.println(completeMultipartUploadResult.getETag());
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
マルチパートアップロードタスクのキャンセル
ossClient.abortMultipartUploadメソッドを呼び出して、マルチパートアップロードタスクをキャンセルできます。 マルチパートアップロードタスクをキャンセルした場合、アップロードIDを使用してパーツをアップロードすることはできません。 アップロードされたパーツは削除されます。
次のサンプルコードは、マルチパートアップロードタスクをキャンセルする方法の例を示しています。
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
public class Demo {
public static void main(String[] args) throws Exception {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path of the object.
String objectName = "exampledir/exampleobject.txt";
// Specify the upload ID. Example: 0004B999EF518A1FE585B0C9360D****. You can obtain the upload ID from the response to the InitiateMultipartUpload operation.
String uploadId = "0004B999EF518A1FE585B0C9360D****";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Cancel the multipart upload task.
AbortMultipartUploadRequest abortMultipartUploadRequest =
new AbortMultipartUploadRequest(bucketName, objectName, uploadId);
ossClient.abortMultipartUpload(abortMultipartUploadRequest);
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
アップロードしたパーツの一覧表示
ossClient.listPartsメソッドを呼び出して、特定のアップロードIDを使用してアップロードされたすべての部品を一覧表示できます。
単純なリストを使用してアップロードされたパーツをリストする
次のサンプルコードは、単純なリストを使用してアップロードされたパーツを一覧表示する方法の例です。
import com.aliyun.oss.ClientException; import com.aliyun.oss.OSS; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.OSSException; import com.aliyun.oss.model.*; public class Demo { public static void main(String[] args) throws Exception { // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Specify the name of the bucket. Example: examplebucket. String bucketName = "examplebucket"; // Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path of the object. String objectName = "exampledir/exampleobject.txt"; // Specify the upload ID. Example: 0004B999EF518A1FE585B0C9360D****. You can obtain the upload ID from the response to the InitiateMultipartUpload operation. You must obtain the upload ID before you call the CompleteMultipartUpload operation to complete the multipart upload task. String uploadId = "0004B999EF518A1FE585B0C9360D****"; // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. String region = "cn-hangzhou"; // Create an OSSClient instance. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { // List uploaded parts. ListPartsRequest listPartsRequest = new ListPartsRequest(bucketName, objectName, uploadId); // Specify the upload ID. //listPartsRequest.setUploadId(uploadId); // Set the maximum number of parts that can be displayed on each page to 100. By default, 1,000 parts are listed. listPartsRequest.setMaxParts(100); // Specify the position from which the list operation starts. Only the parts whose part numbers are greater than the value of this parameter are listed. listPartsRequest.setPartNumberMarker(2); PartListing partListing = ossClient.listParts(listPartsRequest); for (PartSummary part : partListing.getParts()) { // Obtain the part numbers. System.out.println(part.getPartNumber()); // Obtain the size of each part. System.out.println(part.getSize()); // Obtain the ETag of each part. System.out.println(part.getETag()); // Obtain the last modified time of each part. System.out.println(part.getLastModified()); } } catch (OSSException oe) { System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason."); System.out.println("Error Message:" + oe.getErrorMessage()); System.out.println("Error Code:" + oe.getErrorCode()); System.out.println("Request ID:" + oe.getRequestId()); System.out.println("Host ID:" + oe.getHostId()); } catch (ClientException ce) { System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network."); System.out.println("Error Message:" + ce.getMessage()); } finally { if (ossClient != null) { ossClient.shutdown(); } } } }
すべてのマルチパートアップロードイベントの一覧表示
デフォルトでは、listPartsを使用して、一度に最大1,000のアップロードされたパーツを一覧表示できます。 アップロードされたパーツを1,000個以上リストする場合は、次のサンプルコードを実行します。
import com.aliyun.oss.ClientException; import com.aliyun.oss.OSS; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.OSSException; import com.aliyun.oss.model.*; public class Demo { public static void main(String[] args) throws Exception { // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Specify the name of the bucket. Example: examplebucket. String bucketName = "examplebucket"; // Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path of the object. String objectName = "exampledir/exampleobject.txt"; // Specify the upload ID. Example: 0004B999EF518A1FE585B0C9360D****. You can obtain the upload ID from the response to the InitiateMultipartUpload operation. You must obtain the upload ID before you call the CompleteMultipartUpload operation to complete the multipart upload task. String uploadId = "0004B999EF518A1FE585B0C9360D****"; // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. String region = "cn-hangzhou"; // Create an OSSClient instance. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { // List all uploaded parts. PartListing partListing; ListPartsRequest listPartsRequest = new ListPartsRequest(bucketName, objectName, uploadId); do { partListing = ossClient.listParts(listPartsRequest); for (PartSummary part : partListing.getParts()) { // Obtain the part numbers. System.out.println(part.getPartNumber()); // Obtain the size of each part. System.out.println(part.getSize()); // Obtain the ETag of each part. System.out.println(part.getETag()); // Obtain the last modified time of each part. System.out.println(part.getLastModified()); } // Specify the position from which the list operation starts. Only the parts whose part numbers are greater than the value of this parameter are listed. listPartsRequest.setPartNumberMarker(partListing.getNextPartNumberMarker()); } while (partListing.isTruncated()); } catch (OSSException oe) { System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason."); System.out.println("Error Message:" + oe.getErrorMessage()); System.out.println("Error Code:" + oe.getErrorCode()); System.out.println("Request ID:" + oe.getRequestId()); System.out.println("Host ID:" + oe.getHostId()); } catch (ClientException ce) { System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network."); System.out.println("Error Message:" + ce.getMessage()); } finally { if (ossClient != null) { ossClient.shutdown(); } } } }
アップロードされたすべてのパーツをページごとに一覧表示
次のサンプルコードでは、アップロードされたすべてのパーツをページごとに一覧表示し、ページごとに一覧表示するパーツの最大数を指定する方法の例を示します。
import com.aliyun.oss.ClientException; import com.aliyun.oss.OSS; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.OSSException; import com.aliyun.oss.model.*; public class Demo { public static void main(String[] args) throws Exception { // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Specify the name of the bucket. Example: examplebucket. String bucketName = "examplebucket"; // Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path of the object. String objectName = "exampledir/exampleobject.txt"; // Specify the upload ID. Example: 0004B999EF518A1FE585B0C9360D****. You can obtain the upload ID from the response to the InitiateMultipartUpload operation. You must obtain the upload ID before you call the CompleteMultipartUpload operation to complete the multipart upload task. String uploadId = "0004B999EF518A1FE585B0C9360D****"; // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. String region = "cn-hangzhou"; // Create an OSSClient instance. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { // List all uploaded parts by page. PartListing partListing; ListPartsRequest listPartsRequest = new ListPartsRequest(bucketName, objectName, uploadId); // Set the maximum number of parts to list per page to 100. listPartsRequest.setMaxParts(100); do { partListing = ossClient.listParts(listPartsRequest); for (PartSummary part : partListing.getParts()) { // Obtain the part numbers. System.out.println(part.getPartNumber()); // Obtain the size of each part. System.out.println(part.getSize()); // Obtain the ETag of each part. System.out.println(part.getETag()); // Obtain the last modified time of each part. System.out.println(part.getLastModified()); } listPartsRequest.setPartNumberMarker(partListing.getNextPartNumberMarker()); } while (partListing.isTruncated()); } catch (OSSException oe) { System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason."); System.out.println("Error Message:" + oe.getErrorMessage()); System.out.println("Error Code:" + oe.getErrorCode()); System.out.println("Request ID:" + oe.getRequestId()); System.out.println("Host ID:" + oe.getHostId()); } catch (ClientException ce) { System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network."); System.out.println("Error Message:" + ce.getMessage()); } finally { if (ossClient != null) { ossClient.shutdown(); } } } }
マルチパートアップロードタスクの一覧表示
ossClient.listMultipartUploadsメソッドを使用して、進行中のすべてのマルチパートアップロードタスクを一覧表示できます。 進行中のマルチパートアップロードタスクには、開始されたが完了していない、またはキャンセルされたタスクが含まれます。 次の表に、マルチパートアップロードタスクを一覧表示するために設定できるパラメーターを示します。
パラメーター | 説明 | 移動方法 |
prefix | 返されるオブジェクトの名前に含める必要があるプレフィックス。 クエリにプレフィックスを使用する場合、返されるオブジェクト名にはプレフィックスが含まれます。 | ListMultipartUploadsRequest.setPrefix(String prefix) |
delimiter | オブジェクト名のグループ化に使用される文字。 指定されたプレフィックスから区切り文字の最初の出現までの部分文字列を名前に含むオブジェクトは、単一の要素として返されます。 | ListMultipartUploadsRequest.setDelimiter(String delimiter) |
maxUploads | 現在のリストに対して返すマルチパートアップロードタスクの最大数。 最大値は 1000 です。 デフォルト値は 1000 です。 | ListMultipartUploadsRequest.setMaxUploads(Integer maxUploads) |
keyMarker | keyMarkerパラメーターの値の後に名前がアルファベット順になっているオブジェクトを含むすべてのマルチパートアップロードタスクをリストに含めるように指定します。 このパラメーターをuploadIdMarkerパラメーターと一緒に使用して、返された結果の開始位置を指定できます。 | ListMultipartUploadsRequest.setKeyMarker(String keyMarker) |
uploadIdMarker | 返された結果の開始位置。 このパラメーターは、keyMarkerパラメーターと一緒に使用できます。 keyMarkerパラメーターを設定しない場合、uploadIdMarkerパラメーターは無効です。 keyMarkerパラメーターを設定すると、クエリ結果には次の項目が含まれます。
| ListMultipartUploadsRequest.setUploadIdMarker(String uploadIdMarker) |
簡易リストを使用したマルチパートアップロードタスクの一覧表示
次のサンプルコードでは、単純なリストを使用してマルチパートアップロードタスクを一覧表示する方法の例を示します。
import com.aliyun.oss.ClientException; import com.aliyun.oss.OSS; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.OSSException; import com.aliyun.oss.model.*; public class Demo { public static void main(String[] args) throws Exception { // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Specify the name of the bucket. Example: examplebucket. String bucketName = "examplebucket"; // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. String region = "cn-hangzhou"; // Create an OSSClient instance. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { // List multipart upload tasks. By default, 1,000 parts are listed. ListMultipartUploadsRequest listMultipartUploadsRequest = new ListMultipartUploadsRequest(bucketName); MultipartUploadListing multipartUploadListing = ossClient.listMultipartUploads(listMultipartUploadsRequest); for (MultipartUpload multipartUpload : multipartUploadListing.getMultipartUploads()) { // Obtain the upload ID of each multipart upload task. System.out.println(multipartUpload.getUploadId()); // Obtain the name of each multipart upload task. System.out.println(multipartUpload.getKey()); // Obtain the point in time at which each multipart upload task is initiated. System.out.println(multipartUpload.getInitiated()); } } catch (OSSException oe) { System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason."); System.out.println("Error Message:" + oe.getErrorMessage()); System.out.println("Error Code:" + oe.getErrorCode()); System.out.println("Request ID:" + oe.getRequestId()); System.out.println("Host ID:" + oe.getHostId()); } catch (ClientException ce) { System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network."); System.out.println("Error Message:" + ce.getMessage()); } finally { if (ossClient != null) { ossClient.shutdown(); } } } }
レスポンスのisTruncatedパラメーターの値がtrueの場合、nextKeyMarkerとnextUploadIdMarkerの値が返され、次の読み取り操作の開始位置が指定されます。 応答にすべてのマルチパートアップロードタスクが含まれていない場合は、ページごとにマルチパートアップロードタスクを一覧表示します。
すべてのマルチパートアップロードタスクを一覧表示する
既定では、listMultipartUploads操作を呼び出して、一度に最大1,000個のパーツを一覧表示できます。 次のサンプルコードは、パーツ数が1,000を超える場合にすべてのマルチパートアップロードタスクを一覧表示する方法の例を示しています。
import com.aliyun.oss.ClientException; import com.aliyun.oss.OSS; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.OSSException; import com.aliyun.oss.model.*; public class Demo { public static void main(String[] args) throws Exception { // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Specify the name of the bucket. Example: examplebucket. String bucketName = "examplebucket"; // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. String region = "cn-hangzhou"; // Create an OSSClient instance. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { // List multipart upload tasks. MultipartUploadListing multipartUploadListing; ListMultipartUploadsRequest listMultipartUploadsRequest = new ListMultipartUploadsRequest(bucketName); do { multipartUploadListing = ossClient.listMultipartUploads(listMultipartUploadsRequest); for (MultipartUpload multipartUpload : multipartUploadListing.getMultipartUploads()) { // Obtain the upload ID of each multipart upload task. System.out.println(multipartUpload.getUploadId()); // Obtain the object name. System.out.println(multipartUpload.getKey()); // Obtain the point in time at which each multipart upload task is initiated. System.out.println(multipartUpload.getInitiated()); } listMultipartUploadsRequest.setKeyMarker(multipartUploadListing.getNextKeyMarker()); listMultipartUploadsRequest.setUploadIdMarker(multipartUploadListing.getNextUploadIdMarker()); } while (multipartUploadListing.isTruncated()); } catch (OSSException oe) { System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason."); System.out.println("Error Message:" + oe.getErrorMessage()); System.out.println("Error Code:" + oe.getErrorCode()); System.out.println("Request ID:" + oe.getRequestId()); System.out.println("Host ID:" + oe.getHostId()); } catch (ClientException ce) { System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network."); System.out.println("Error Message:" + ce.getMessage()); } finally { if (ossClient != null) { ossClient.shutdown(); } } } }
すべてのマルチパートアップロードタスクをページごとに一覧表示する
次のサンプルコードは、すべてのマルチパートアップロードタスクをページごとに一覧表示する方法の例を示しています。
import com.aliyun.oss.ClientException; import com.aliyun.oss.OSS; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.OSSException; import com.aliyun.oss.model.*; public class Demo { public static void main(String[] args) throws Exception { // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Specify the name of the bucket. Example: examplebucket. String bucketName = "examplebucket"; // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. String region = "cn-hangzhou"; // Create an OSSClient instance. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { // List multipart upload tasks. MultipartUploadListing multipartUploadListing; ListMultipartUploadsRequest listMultipartUploadsRequest = new ListMultipartUploadsRequest(bucketName); // Specify the number of multipart upload tasks to list on each page. listMultipartUploadsRequest.setMaxUploads(50); do { multipartUploadListing = ossClient.listMultipartUploads(listMultipartUploadsRequest); for (MultipartUpload multipartUpload : multipartUploadListing.getMultipartUploads()) { // Obtain the upload ID of each multipart upload task. System.out.println(multipartUpload.getUploadId()); // Obtain the name of each multipart upload task. System.out.println(multipartUpload.getKey()); // Obtain the point in time at which each multipart upload task is initiated. System.out.println(multipartUpload.getInitiated()); } listMultipartUploadsRequest.setKeyMarker(multipartUploadListing.getNextKeyMarker()); listMultipartUploadsRequest.setUploadIdMarker(multipartUploadListing.getNextUploadIdMarker()); } while (multipartUploadListing.isTruncated()); } catch (OSSException oe) { System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason."); System.out.println("Error Message:" + oe.getErrorMessage()); System.out.println("Error Code:" + oe.getErrorCode()); System.out.println("Request ID:" + oe.getRequestId()); System.out.println("Host ID:" + oe.getHostId()); } catch (ClientException ce) { System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network."); System.out.println("Error Message:" + ce.getMessage()); } finally { if (ossClient != null) { ossClient.shutdown(); } } } }
関連ドキュメント
マルチパートアップロードの実行に使用する完全なサンプルコードについては、『GitHub』をご参照ください。
マルチパートアップロードには3つのAPI操作が含まれます。 操作の詳細については、以下のトピックを参照してください。
マルチパートアップロードタスクをキャンセルするために呼び出すことができるAPI操作の詳細については、「AbortMultipartUpload」をご参照ください。
アップロードされたパーツを一覧表示するために呼び出すことができるAPI操作の詳細については、「ListParts」をご参照ください。
実行中のすべてのマルチパートアップロードタスクを一覧表示するために呼び出すことができるAPI操作の詳細については、「ListMultipartUploads」をご参照ください。 進行中のマルチパートアップロードタスクには、開始されたが完了していない、またはキャンセルされたタスクが含まれます。