百度智能云

All Product Document

          Object Storage

          Object Management

          Object Uploading

          The Simplest Uploading

          • Basic procedure

            1.Create an instance of the BOSClient class. 2.To call BOSClient.putObject (), upload object through the following four ways: Files, data streams, binary strings, and character strings. 3.As for returned PutObjectResponse type, execute getETag() to access ETag uploaded successfully.

          • Sample Code

              // Access specified files
              File file = new File(<FilePath>);     //Designate file path. 
                  
              // Upload object as file
              PutObjectResponse putObjectFromFileResponse = client.putObject(<BucketName>, <ObjectKey>, file);
              
              // Access data stream
              InputStream inputStream = new FileInputStream(<FilePath>);
              
              // Upload object as the data stream
              PutObjectResponse putObjectResponseFromInputStream = client.putObject(<BucketName>, <ObjectKey>, inputStream);
              
              // Upload object as the binary string
              PutObjectResponse putObjectResponseFromByte = client.putObject(<BucketName>, <ObjectKey>, <byte>);
              
              // Upload object as the character string
              PutObjectResponse putObjectResponseFromString = client.putObject(<BucketName>, <ObjectKey>, <string>);
                  
              // Print ETag
              System.out.println(putObjectFromFileResponse.getETag());

            Note: Upload object to BOS in the file form. objects no more than 5 GB can be uploaded through putObject. After the putObject request is successfully processed, BOS will return the ETag of object as a file identifier in the Header.

          • Complete example

              import java.io.File;
              import java.io.FileInputStream;
              import java.io.FileNotFoundException;
              import java.io.InputStream;
              import android.app.Activity;
              import android.os.Bundle;
              import com.baidubce.BceClientException;
              import com.baidubce.BceServiceException;
              import com.baidubce.auth.DefaultBceCredentials;
              import com.baidubce.development.R;
              import com.baidubce.services.bos.BosClient;
              import com.baidubce.services.bos.BosClientConfiguration;
              import com.baidubce.services.bos.model.PutObjectResponse;
              ​    
              public class ExampleActivity extends Activity {
              
                private String bucketName = <BucketName>;
                private String objectKey = <ObjectKey>;
                byte[] b = null;
                String str = <PutString>;
              
                @Override
                protected void onCreate(Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
                  setContentView(R.layout.activity_main);
                  new Thread(new Runnable() {
                      @Override
                      public void run() {
                          try {
                              BosClientConfiguration config = new BosClientConfiguration();
                              config.setCredentials(new DefaultBceCredentials(<AccessKeyID>, <SecretAccessKey>));
                              config.setEndpoint(<EndPoint>);
                              BosClient client = new BosClient(config);
                              
                              // Access specified files
                              File file = new File("/path/to/file.zip");
                              
                              // Upload object as file
                              PutObjectResponse putObjectFromFileResponse = client.putObject(<BucketName>, <ObjectKey>, file);
                              
                              // Access data stream
                              InputStream inputStream = new FileInputStream("/path/to/test.zip");
                              
                              // Upload object as the data stream
                              PutObjectResponse putObjectResponseFromInputStream = client.putObject(<BucketName>, <ObjectKey>, inputStream);
                              
                              // Upload object as the binary string
                              PutObjectResponse putObjectResponseFromByte = client.putObject(<BucketName>, <ObjectKey>, b);
                              
                              // Upload object as the character string
                              PutObjectResponse putObjectResponseFromString = client.putObject(<BucketName>, <ObjectKey>, str);
                              
                              // Print ETag
                              System.out.println(putObjectFromFileResponse.getETag());
                              
                          } catch (BceServiceException e) {
                              System.out.println("Error ErrorCode: " + e.getErrorCode());
                              System.out.println("Error RequestId: " + e.getRequestId());
                              System.out.println("Error StatusCode: " + e.getStatusCode());
                              System.out.println("Error Message: " + e.getMessage());
                              System.out.println("Error ErrorType: " + e.getErrorType());
                          } catch (BceClientException e) {
                              System.out.println("Error Message: " + e.getMessage());
                          } catch (FileNotFoundException e) {
                              // TODO Auto-generated catch block
                              e.printStackTrace();
                          } 
                      }
                  }).start();
              }}

          Set the Copy Attribute of Object

          The Copyobject interface is used to copy an existing object to another object. During the copying process, the Etag or modification status of source object is checked to define whether to execute this operation. The following shows parameters in detail:

          Name Type Description Required or not
          x-bce-copy-source-if-match String If ETag value of source object is equal to ETag provided by the user, copy operation is performed, otherwise the copy fails. No
          x-bce-copy-source-if-none-match String If ETag value of source object is equal to ETag provided by the user, copy operation is performed, otherwise copy fails. No
          x-bce-copy-source-if-unmodified-since String If source object is not modified after x-bce-copy-source-if-unmodified-since, copy operation is performed, otherwise copy fails. No
          x-bce-copy-source-if-modified-since String If source object is modified after x-bce-copy-source-if-modified-since, copy operation is performed, otherwise copy fails. No
          • Sample Code

              // Initialize BosClient
              BosClient client = ...;
              
              // Create CopyObjectRequest
              CopyObjectRequest copyObjectRequest = new CopyObjectRequest(srcBucketName, srcKey, destBucketName, destKey);
              
              // Create Metadata
              Map<String, String> userMetadata = new HashMap<String, String>();
              userMetadata.put("<user-meta-key>","<user-meta-value>");
              ObjectMetadata meta = new ObjectMetadata();
              meta.setUserMetadata(userMetadata);
              copyObjectRequest.setNewObjectMetadata(meta);
              
              //copy-source-if-match
              copyObjectRequest.withETag("111111111183bf192b57a4afc76fa632");
              //copy-source-if-none-match
              copyObjectRequest.withNoMatchingETagConstraint("111111111183bf192b57a4afc76fa632");
              
              Date modifiedSinceConstraint = new Date();    
              SimpleDateFormat df = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z", Locale.UK);  
              df.setTimeZone(new java.util.SimpleTimeZone(0, "GMT"));        
              String date = df.format(modifiedSinceConstraint);
              
              //copy-source-if-modified-since
              copyObjectRequest.withModifiedSinceConstraint(date);
              
              //copy-source-if-unmodified-since
              copyObjectRequest.withUnmodifiedSinceConstraint(date);
              
              // 复制Object
              CopyObjectResponse copyObjectResponse = client.copyObject(copyObjectRequest);

          Set the Http Header of Object

          Under BOS, Http Header setting is available during object uploading.

          • Basic procedure

            1.Create an instance of ObjectMetadata. 2.Execute such methods as setContentLength()/setContentType() to set the Http Header. 3.Add meta (being already set) as a parameter to client.putObject().

          • Sample Code

              // Create an instance of ObjectMetadata. 
              ObjectMetadata meta = new ObjectMetadata(); 
              
              // Set the size of ContentLength. 
              meta.setContentLength(<Length>); 
              
              // Set ContentType. 
              meta.setContentType("application/json"); 
              
              client.putObject(<BucketName>,<ObjectKey>, content, meta); 

            Note: The following attributes of header can be set, including: "Cache-Control", "Content-Encoding", "Content-Disposition", "Expires"

          • Complete example

              import java.io.FileInputStream;
              import java.io.FileNotFoundException;
              import java.io.InputStream;
              import android.app.Activity;
              import android.os.Bundle;
              import com.baidubce.BceClientException;
              import com.baidubce.BceServiceException;
              import com.baidubce.auth.DefaultBceCredentials;
              import com.baidubce.demo.R;
              import com.baidubce.services.bos.BosClient;
              import com.baidubce.services.bos.BosClientConfiguration;
              import com.baidubce.services.bos.model.ObjectMetadata;
              import com.baidubce.services.bos.model.PutObjectResponse;
              
              public class ExampleActivity extends Activity {
              
              private String bucketName = <BucketName>;
              private String objectKey = <ObjectKey>;
              
              @Override
              protected void onCreate(Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
                  setContentView(R.layout.activity_main);
                  new Thread(new Runnable() {
                      @Override
                      public void run() {
                          try {
                              BosClientConfiguration config = new BosClientConfiguration();
                              config.setCredentials(new DefaultBceCredentials(<AccessKeyID>, <SecretAccessKey>));
                              config.setEndpoint(<EndPoint>);
                              BosClient client = new BosClient(config);
                              
                              // Access data stream
                              InputStream inputStream = new FileInputStream("/path/to/test.zip");
                              
                              // Create an instance of ObjectMetadata
                              ObjectMetadata meta = new ObjectMetadata();
                              
                              // Set the size of ContentLength
                              meta.setContentLength(1000);
                              
                              // Set ContentType
                              meta.setContentType("application/json");
                              
                              PutObjectResponse putObjectResponseFromInputStream = client.putObject(bucketName, objectKey, inputStream, meta);
                              
                               // Print ETag
                              System.out.println(putObjectResponseFromInputStream.getETag());
                              
                          } catch (BceServiceException e) {
                              System.out.println("Error ErrorCode: " + e.getErrorCode());
                              System.out.println("Error RequestId: " + e.getRequestId());
                              System.out.println("Error StatusCode: " + e.getStatusCode());
                              System.out.println("Error Message: " + e.getMessage());
                              System.out.println("Error ErrorType: " + e.getErrorType());
                          } catch (BceClientException e) {
                              System.out.println("Error Message: " + e.getMessage());
                          } catch (FileNotFoundException e) {
                              // TODO Auto-generated catch block
                              e.printStackTrace();
                          } 
                      }
                  }).start();
              }}

          Custom Metadata

          Custom metadata is available under BOS for object description.

          • Basic procedure

            1.Create an instance of ObjectMetadata. 2.Execute addUserMetadata() to customize the metadata of Http Header. 3.Add meta (being already set) as a parameter to client.putObject().

          • Sample Code

              // Set the name value of customized metadata as my-data. 
              meta.addUserMetadata("name", "my-data"); 	  
              
              // Upload object  
              client.putObject(<BucketName>,<ObjectKey>,<Content>, meta); 

            Note: As for the above code, users have customized a metadata of which the name is "name" and the value is "my-data". When users download this object, they can get metadata together. One object possesses similar parameters, but the total size of User Meta bellows 2KB.

          • Complete example

              import java.io.FileInputStream;
              import java.io.FileNotFoundException;
              import java.io.InputStream;
              import android.app.Activity;
              import android.os.Bundle;
              import com.baidubce.BceClientException;
              import com.baidubce.BceServiceException;
              import com.baidubce.auth.DefaultBceCredentials;
              import com.baidubce.demo.R;
              import com.baidubce.services.bos.BosClient;
              import com.baidubce.services.bos.BosClientConfiguration;
              import com.baidubce.services.bos.model.ObjectMetadata;
              import com.baidubce.services.bos.model.PutObjectResponse;
              
              public class ExampleActivity extends Activity {
              
              private String bucketName = <BucketName>;
              private String objectKey = <ObjectKey>;
              
              @Override
              protected void onCreate(Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
                  setContentView(R.layout.activity_main);
                  new Thread(new Runnable() {
                      @Override
                      public void run() {
                          try {
                              BosClientConfiguration config = new BosClientConfiguration();
                              config.setCredentials(new DefaultBceCredentials(<AccessKeyID>, <SecretAccessKey>));
                              config.setEndpoint(<EndPoint>);
                              BosClient client = new BosClient(config);
                              
                              // Access data stream
                              InputStream inputStream = new FileInputStream("/path/to/test.zip");
                              
                              // Create an instance of ObjectMetadata
                              ObjectMetadata meta = new ObjectMetadata();
                              
                              // Customize Metadata
                              meta.addUserMetadata("name", "my-data");	    
                              
                              PutObjectResponse putObjectResponseFromInputStream = client.putObject(<BucketName>, <ObjectKey>, inputStream, meta);
                              
                               // Print ETag
                              System.out.println(putObjectResponseFromInputStream.getETag());
                              
                          } catch (BceServiceException e) {
                              System.out.println("Error ErrorCode: " + e.getErrorCode());
                              System.out.println("Error RequestId: " + e.getRequestId());
                              System.out.println("Error StatusCode: " + e.getStatusCode());
                              System.out.println("Error Message: " + e.getMessage());
                              System.out.println("Error ErrorType: " + e.getErrorType());
                          } catch (BceClientException e) {
                              System.out.println("Error Message: " + e.getMessage());
                          } catch (FileNotFoundException e) {
                              // TODO Auto-generated catch block
                              e.printStackTrace();
                          } 
                      }
                  }).start();
              }}

          Upload Object in Append Way

          AppendObject is available under BOS. That is, uploading files through additional writing, which is applicable to such real-time video file uploading as log addition and live broadcast. Type of object created through appendObject operation is Appendable object, and data can be appended to the object; while object uploaded through Putobject is Normal object, and data cannot be written or appended. appendObject size is 0-5G.

          • Sample Code

              public void AppendObject(BosClient client, String bucketName, String objectKey, byte[] byte1, String string1) {
                    // Access specified files
                    File file = new File("/path/to/file.zip");
                    // Access data stream
                    InputStream inputStream = new FileInputStream("/path/to/test.zip");
              
                    // Upload object as file
                    AppendObjectResponse appendObjectFromFileResponse = client.appendObject(bucketName, objectKey, file);
                    // Upload object as the data stream
                    AppendObjectResponse appendObjectResponseFromInputStream = client.appendObject(bucketName, objectKey, inputStream);
                    // Upload object as the binary string
                    AppendObjectResponse appendObjectResponseFromByte = client.appendObject(bucketName, objectKey, byte1);
                    // Upload object as the character string
                    AppendObjectResponse appendObjectResponseFromString = client.appendObject(bucketName, objectKey, string1);
                    
                    // Enrich AppendFile with content
                    Long nextOffset = appendObjectFromFileResponse.getNextAppendOffset();
                    AppendObjectRequest request =new AppendObjectRequest(bucketName, objectKey,
                    RestartableInputStream.wrap(string1.getBytes()));
                    request.withOffset(nextOffset);
                    AppendObjectResponse appendResponse = client.appendObject(request);      
              }

          Check Uploading Process

          Uploading status is available during the uploading process with Android SDK. Currently, Putobject, appendObject and UploadPart interfaces are available. Corresponding Request (PutObjectRequest, AppendObjectRequest, and UploadPartRequest) must be made to use the interface of uploading status.

          The following is the callback interface of upload progress provided by SDK. You can define operations needed during uploading, such as updating interface.

          public interface BceProgressCallback<T extends AbstractBceRequest> { 
          	  // request is an upload request
          	  // currentSize is the size of current uploading one. (Unit: byte) 
          	  // totalSize is the total size of the ones to upload in this request. (Unit: byte) 
                void onProgress(T request, long currentSize, long totalSize); 
          • Putobject sample code:

              //
             PutObjectRequest request = new PutObjectRequest(this.bucketName, "test", file);
             ObjectMetadata objectMetadata = new ObjectMetadata();
             objectMetadata.setContentType("text/plain");
             request.setObjectMetadata(objectMetadata);
             request.setProgressCallback(new BosProgressCallback<PutObjectRequest>() {
                 @Override
                 public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                     Log.e(currentSize + "", totalSize + "");
                 }
             });
             String eTag = this.client.putObject(request).getETag();
          • appendObject sample code:

             ObjectMetadata objectMetadata = new ObjectMetadata();
             objectMetadata.setContentType("text/plain");
             AppendObjectRequest request = new AppendObjectRequest(this.bucketName, "test", file);
             request.setObjectMetadata(objectMetadata);
             AppendObjectResponse response = this.client.appendObject(request);
             Long nextOffset = response.getNextAppendOffset();
             request.withOffset(nextOffset);
             request.setProgressCallback(new BosProgressCallback<AppendObjectRequest>() {
                 @Override
                 public void onProgress(AppendObjectRequest request, long currentSize, long totalSize) {
                     Log.e(currentSize + "", totalSize + "");
                 }
             });
             response = this.client.appendObject(request);
          • UploadPart sample code:

            UploadPartRequest request = new UploadPartRequest().withBucketName(this.bucketName)
                    .withKey("test").withUploadId(uploadId).withPartNumber(1).withPartSize(8000)
                    .withInputStream(fis);
            request.setProgressCallback(new BosProgressCallback<UploadPartRequest>() {
                @Override
                public void onProgress(UploadPartRequest request, long currentSize, long totalSize) {
                    Log.e(currentSize + "", totalSize + "");
                }
            });
            UploadPartResponse response = this.client.uploadPart(request);

            Currently, under SDK, the callback grain of uploading status by default is 2048 bytes. The callback grain more suitable to App can be set through the following methods.

            BosClientConfiguration config=new BosClientConfiguration(); config.setUploadSegmentPart(1024);

          Note: The value must be 1-8192, otherwise the Android SDK will set it as 2048.

          Interface Cancelation

          This request can be canceled halfway with Android SDK, and the remaining data of the uploading request will no longer be uploaded to BOS. The cancelation of the downloading request will cut the connection, and the operation in progress will face Request is canceled!Abnormal

          All BOS operation can use the cancelation interface. However, the completed requests cannot be canceled, and the operation completed will not bring abnormal signals.

          // Take interface cancelation as an example
          final PutObjectRequest req = new PutObjectRequest(<BucketName>, <ObjectName>,
                   new FileInputStream(<FilePath>));
          Runnable cancelTask = new Runnable() {
              @Override
              public void run() {
                  try {
                      Thread.sleep(100);
                  } catch (InterruptedException e) {
                      e.printStackTrace()
                  }
                  // Cancel this uploading request
                  req.cancel();
              }
          };
          new Thread(cancelTask).start();
          client.putObject(req);

          Synchronous Callback

          Under Android SDK, BOS server synchronous callback interface is available. Setting the process parameter in PutObjectRequest to help BOS server activate the callback interface actively to inform customers of uploading completion.

          PutObjectRequest request = new PutObjectRequest({bucket}, {object}, {inputStream});
          // Set parameter x-bce-process
          request.setProcess({x-bce-process});
          PutObjectResponse response = client.putObject(request);
          // Access the returned http status code
          int statusCode = response.getHttpResponse().getStatusCode();
          // Access the data from the returned callback interface
          string callbackString = response.getServerCallbackReturnBody();

          View the Object in Bucket

          View the object list in bucket.

          • Basic procedure

            1.Create an instance of the BOSClient class. 2.The execution of BOSClient.listobjects(BucketName) method brings the example of ListobjectsResponse. 3.Getbuckets()/getOwner()/getMetadata() can be performed on ListobjectsResponse.

          • Sample Code

              // Access all object information of specified bucket. 
              ListobjectsResponse listing = client.listObjects(<BucketName>); 
              
              // Traverse all objects. 
              for (BosObjectSummary objectSummary : listing.getContents()) { 
                  System.out.println("ObjectKey: " + objectSummary.getKey()); 
              } 

            Note: The listobjects( ) method returns the ListobjectsResponse object, which contains the result of this listobject request. You can access the description information of all objects through the getContents method in ListobjectsResponse.

            • By default, only 1,000 objects are returned and the IsTruncated value is True if bucket has over 1,000 objects. Besides, NextMarker is returned as the starting point for the next reading.
            • Use the Marker parameter to access more objects in batches. Refer to [query expansion](#query expansion).
          • Complete example

              import android.app.Activity;
              import android.os.Bundle;
              import com.baidubce.BceClientException;
              import com.baidubce.BceServiceException;
              import com.baidubce.auth.DefaultBceCredentials;
              import com.baidubce.demo.R;
              import com.baidubce.services.bos.BosClient;
              import com.baidubce.services.bos.BosClientConfiguration;
              import com.baidubce.services.bos.model.BosObjectSummary;
              import com.baidubce.services.bos.model.ListObjectsResponse;
              
              public class ExampleActivity extends Activity {
              
              private String bucketName = <BucketName>;
              
              @Override
              protected void onCreate(Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
                  setContentView(R.layout.activity_main);
                  new Thread(new Runnable() {
                      @Override
                      public void run() {
                          try {
                              BosClientConfiguration config = new BosClientConfiguration();
                              config.setCredentials(new DefaultBceCredentials(<AccessKeyId>, <SecretAccessKey>));
                              config.setEndpoint(<EndPoint>);
                              BosClient client = new BosClient(config);
                              
                              // Access all object information of specified bucket
                              ListObjectsResponse listing = client.listObjects(<BucketName>);
              
                              // Traverse all objects
                              for (BosObjectSummary objectSummary : listing.getContents()) {
                                  System.out.println("ObjectKey: " + objectSummary.getKey());
                              }               	                    
                              
                          } catch (BceServiceException e) {
                              System.out.println("Error ErrorCode: " + e.getErrorCode());
                              System.out.println("Error RequestId: " + e.getRequestId());
                              System.out.println("Error StatusCode: " + e.getStatusCode());
                              System.out.println("Error Message: " + e.getMessage());
                              System.out.println("Error ErrorType: " + e.getErrorType());
                          } catch (BceClientException e) {
                              System.out.println("Error Message: " + e.getMessage());
                          }
                      }
                  }).start();
              }}

          Query Expansion

          For more query expansion operation setting, you can set the ListobjectsRequest parameter. The extended parameters available to set in ListobjectsRequest are as follows:

          Parameter name Description Default value
          MaxKeys Set the maximum number of objects returned this time as 1000. 1000
          Prefix Sets the prefix of ObjectKey, which covers and starts with the value of Prefix.
          is usually used together with Delimiter in [searching simulation folders](#searching simulation folders).
          -
          Delimiter A delimiter, used to make ObjectKey hierarchies.
          is usually used together with Prefix in [searching simulation folders](#searching simulation folders).
          The ObjectKey between Prefix and Delimiter character (showing for the first time) is called: CommonPrefixes
          -
          Marker A character string, used to set the starting position of the returned result.
          After the Marker value is set, the returned object returns alphabetically after that value.
          -
          • Basic procedure

            1.Create an instance of the ListobjectsRequest class. 2.Execute such methods as setDelimiter/setMarker()/setPrefix() in ListobjectsRequest for more query expansion operation. 3.Create an example of BOSClient and execute listobjects(listobjectsRequest).

          • Sample Code

              // Create the request of ListobjectsRequest
              ListObjectsRequest listObjectsRequest = new ListObjectsRequest(<BucketName>);  
              
              // Set query expansion parameters
              listObjectsRequest.setDelimiter(<Delimiter>);
              listObjectsRequest.setMarker(<Marker>);
              ...   
              ListObjectsResponse listing = client.listObjects(listObjectsRequest);

            Note: An overloaded method of listobjects is called and requests are completed by ListobjectsRequest in the above codes.

          • Complete example

            Example I:

            import android.app.Activity;
            import android.os.Bundle;
            import com.baidubce.BceClientException;
            import com.baidubce.BceServiceException;
            import com.baidubce.auth.DefaultBceCredentials;
            import com.baidubce.demo.R;
            import com.baidubce.services.bos.BosClient;
            import com.baidubce.services.bos.BosClientConfiguration;
            import com.baidubce.services.bos.model.BosObjectSummary;
            import com.baidubce.services.bos.model.ListObjectsRequest;
            import com.baidubce.services.bos.model.ListObjectsResponse;
            
            public class ExampleActivity extends Activity {
            
            private String bucketName = <BucketName>;
            
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            BosClientConfiguration config = new BosClientConfiguration();
                            config.setCredentials(new DefaultBceCredentials(<AccessKeyID>, <SecretAccessKey>));
                            config.setEndpoint(<EndPoint>);
                            BosClient client = new BosClient(config);
                            
                            // Create the request of ListobjectsRequest
                            ListObjectsRequest listObjectsRequest = new ListObjectsRequest(<BucketName>); 
                            
                            // Parameter setting
                            listObjectsRequest.setDelimiter("/");
                            listObjectsRequest.setMarker("123");
                            listObjectsRequest.setMaxKeys(100);
                            listObjectsRequest.setPrefix("fun");
                            
                            // Access all object information (consistent with afore-mentioned conditions) of specified bucket
                            ListObjectsResponse listing = client.listObjects(listObjectsRequest);
            
                            // Traverse all objects
                            for (BosObjectSummary objectSummary : listing.getContents()) {
                                System.out.println("ObjectKey: " + objectSummary.getKey());
                            }                	
                            
                        } catch (BceServiceException e) {
                            System.out.println("Error ErrorCode: " + e.getErrorCode());
                            System.out.println("Error RequestId: " + e.getRequestId());
                            System.out.println("Error StatusCode: " + e.getStatusCode());
                            System.out.println("Error Message: " + e.getMessage());
                            System.out.println("Error ErrorType: " + e.getErrorType());
                        } catch (BceClientException e) {
                            System.out.println("Error Message: " + e.getMessage());
                        }
                    }
                }).start();
            }}

            Example II: Use the complete example of Nextmarker.

            import android.app.Activity;
            import android.os.Bundle;
            import com.baidubce.BceClientException;
            import com.baidubce.BceServiceException;
            import com.baidubce.auth.DefaultBceCredentials;
            import com.baidubce.demo.R;
            import com.baidubce.services.bos.BosClient;
            import com.baidubce.services.bos.BosClientConfiguration;
            import com.baidubce.services.bos.model.BosObjectSummary;
            import com.baidubce.services.bos.model.ListObjectsRequest;
            import com.baidubce.services.bos.model.ListObjectsResponse;
            
            public class ExampleActivity extends Activity {
            
            private String bucketName = <BucketName>;
            
            @Override
            protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
              new Thread(new Runnable() {
                  @Override
                  public void run() {
                     try {
                        BosClientConfiguration config = new BosClientConfiguration();
                        config.setCredentials(new DefaultBceCredentials(<AccessKeyId>, <SecretAccessKey>);
                        config.setEndpoint(<EndPoint>);
                        BosClient client = new BosClient(config);
                        ListObjectsRequest listObjectsRequest = new ListObjectsRequest(<BucketName>);
                        listObjectsRequest.setMarker("");
                        listObjectsRequest.setMaxKeys(20);
                        listObjectsRequest.setDelimiter(BceConfig.BOS_DELIMITER);
                        ListObjectsResponse listObjectsResponse = client.listObjects(listObjectsRequest);
                        String nextMark = "";
                        if(listObjectsResponse.isTruncated()){
                           nextMark = listObjectsResponse.getNextMarker();
                        }
                            
                       ListObjectsRequest listObjectsRequest2 = new ListObjectsRequest(<BucketName>);
                       listObjectsRequest2.setMarker(nextMark);
                       listObjectsRequest2.setMaxKeys(20);
                       listObjectsRequest2.setDelimiter(BceConfig.BOS_DELIMITER);
                       ListObjectsResponse listing = client.listObjects(listObjectsRequest2);
                            
                       for (BosObjectSummary objectSummary : listing.getContents()) {
                           System.out.println("ObjectKey: " + objectSummary.getKey());
                        }                
            
                      } catch (BceServiceException e) {
                        System.out.println("Error ErrorCode: " + e.getErrorCode());
                        System.out.println("Error RequestId: " + e.getRequestId());
                        System.out.println("Error StatusCode: " + e.getStatusCode());
                        System.out.println("Error Message: " + e.getMessage());
                        System.out.println("Error ErrorType: " + e.getErrorType());
                     } catch (BceClientException e) {
                        System.out.println("Error Message: " + e.getMessage());
                     }
                  }
                }).start();
            }}

          Search for Simulation Folders

          BOS, as a (<Key>,<Value>) storage system, does not have "folders" in principle. But folder function simulation can be realized by Delimiter and Prefix parameters.

          Suppose bucket have 5 files: bos.jpg, fun/, fun/test.jpg, fun/movie/001.avi, fun/movie/007.avi ("/" can be used as a delimiter to simulate folders.)

          Lists All Files in Simulation Folders Recursively

          Set the Prefix parameter to access all files in a simulation folder:

          // Create the request of ListobjectsRequest
          ListObjectsRequest listObjectsRequest = new ListObjectsRequest(<BucketName>);
                  
          // Recursively list all files in the fun folder
          listObjectsRequest.setPrefix("fun/");
                  
          ListObjectsResponse listing = client.listObjects(listObjectsRequest);
                  
          // Traverse all objects
          System.out.println("Objects:");
          for (BosObjectSummary objectSummary : listing.getContents()) {
             System.out.println(objectSummary.getKey());
          }

          Output:

          Objects: 
          fun/ 
          fun/movie/001.avi 
          fun/movie/007.avi 
          fun/test.jpg 

          Check the Files and Subfolders in Simulation Folders

          The files and subfolders in simulation folders can be listed with the combination of Prefix and Delimiter:

          // Create the request of ListobjectsRequest
          ListObjectsRequest listObjectsRequest = new ListObjectsRequest(<BucketName>);
                  
          //  Designate "/" as the delimiter for of simulation folders
          listObjectsRequest.setDelimiter("/");
                  
          // List all files and subfolders in fun folders
          listObjectsRequest.setPrefix("fun/");
                  
          ListObjectsResponse listing = client.listObjects(listObjectsRequest);
                  
          // ListobjectsResponse listing
          System.out.println("Objects:");
          for (BosObjectSummary objectSummary : listing.getContents()) {
             System.out.println(objectSummary.getKey());
          }
                  
          // Traverse all objects
          System.out.println("\nCommonPrefixs:");
          for (String commonPrefix : listing.getCommonPrefixes()) {
             System.out.println(commonPrefix);
          }

          Output:

          Objects: 
          fun/ 
          fun/test.jpg 
              
          CommonPrefixs: 
          fun/movie/

          Note:

          The returned result in the list of objects is the files in fun folders. All subfolders under fun folder are shown in the list of CommonPrefixs. It is clear that the fun/movie/001.avi file and fun/movie/007.avi file are not listed because they are the files in the movie subfolder under the fun folder.

          Access Object

          Access Object Easily

          You can read object in a stream through the following codes.

          • Basic procedure

            1.Create an instance of the BOSClient class. 2.Execute BOSClient.getobject() method to return to the specified BosObject. 3.Read BosObject into the stream and then operate on the stream.

          • Sample Code

              // Get object and return BosObject 
              BosObject object = client.getObject(<BucketName>,<ObjectKey>); 
              
              // Get objectMeta. 
              ObjectMetadata meta = object.getObjectMetadata(); 
              
              // Get the input stream of object 
              InputStream objectContent = object.getObjectContent(); 
              
              // Process object 
              ...
              
              // Close stream 
              objectContent.close(); 

            Note:

            • BosObject contains information of object, including the bucket where the object is located, object name, MetaData and an input stream. You can read the contents of the object into files or memory by operating the input stream.
            • ObjectMetadata contains the ETag defined when the object is uploaded, the Http Header, and the custom metadata.
            • Through the getObjectContent () method of BosObject, you can also get the input stream that returns the object, and read the input stream to manipulate the contents of the object.
          • Complete example

              import java.io.BufferedReader;
              import java.io.IOException;
              import java.io.InputStream;
              import java.io.InputStreamReader;
              import android.app.Activity;
              import android.os.Bundle;
              import com.baidubce.BceClientException;
              import com.baidubce.BceServiceException;
              import com.baidubce.auth.DefaultBceCredentials;
              import com.baidubce.demo.R;
              import com.baidubce.services.bos.BosClient;
              import com.baidubce.services.bos.BosClientConfiguration;
              import com.baidubce.services.bos.model.BosObject;
              import com.baidubce.services.bos.model.ObjectMetadata;
              
              public class ExampleActivity extends Activity {
              
              private String bucketName = <BucketName>;
              private String objectKey = <ObjectKey>;
              
              @Override
              protected void onCreate(Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
                  setContentView(R.layout.activity_main);
                  new Thread(new Runnable() {
                      @Override
                      public void run() {
                          try {
                              BosClientConfiguration config = new BosClientConfiguration();
                              config.setCredentials(new DefaultBceCredentials(<AccessKeyID>, <SecretAccessKey>));
                              config.setEndpoint(<EndPoint>);
                              BosClient client = new BosClient(config);
              
                              // Get object and return BosObject
                              BosObject object = client.getObject(<BucketName>, <ObjectKey>);
              
                              // Get objectMeta
                              ObjectMetadata meta = object.getObjectMetadata();
              
                              // Get the input stream of object
                              InputStream objectContent = object.getObjectContent();
              
                              // Process Object
                              FileOutputStream fos=new FileOutputStream(android.os.Environment.getExternalStorageDirectory()+"/1/file");  
                              byte[] buffer=new byte[<bufferSize>];  
                              int count=0;  
                              while ((count=objectContent.read(buffer))>=0) {  
                                  fos.write(buffer,0,count);  
                              }  
                              
                              System.out.println(meta.getETag());
                              System.out.println(meta.getContentLength());
                              
                              // Close stream
                              objectContent.close();
                              fos.close(); 
                              
                          } catch (BceServiceException e) {
                              System.out.println("Error ErrorCode: " + e.getErrorCode());
                              System.out.println("Error RequestId: " + e.getRequestId());
                              System.out.println("Error StatusCode: " + e.getStatusCode());
                              System.out.println("Error Message: " + e.getMessage());
                              System.out.println("Error ErrorType: " + e.getErrorType());
                          } catch (BceClientException e) {
                              System.out.println("Error Message: " + e.getMessage());
                          } catch (IOException e) {
                              // TODO Auto-generated catch block
                              e.printStackTrace();
                          }
                      }
                  }).start();
              }}

          Get Object through GetObjectRequest

          For more features, you can get object by using GetObjectRequest.

          • Basic procedure

            1.Create an instance of the GetObjectRequest class. 2.Execute setRange( ) on GetObjectRequest to get the required byte data in object. 3.Execute the client.getobject ( ).

          • Sample Code

              // Create a GetObjectRequest
              GetObjectRequest getObjectRequest = new GetObjectRequest(<BucketName>, <ObjectKey>);
              
              // Get data in the range of 0-100 bytes
              getObjectRequest.setRange(0, 100);
              
              // Get object and return BosObject
              BosObject object = client.getObject(getObjectRequest);

            Note: You can set the range to return object through setRange( ) method of getObjectRequest. You can use this function for segmented download of file and breakpoint continued upload.

          Get Download Status

          You can get the download status information through the callback function.

          The following is the callback interface of download status provided by SDK. You can define operations needed during uploading process, such as updating interface.

          public interface BceProgressCallback<T extends AbstractBceRequest> { 
          	  // request is a download request. 
          	  // currentSize is the size of current downloading one. (Unit: byte) 
          	  // totalSize is the total size of the ones to download in this request. (Unit: byte) 
                void onProgress(T request, long currentSize, long totalSize); 
          • Sample Code

            GetObjectRequest request = new GetObjectRequest()
                    .withBucketName(this.bucketName)
                    .withKey(objectKey)
                    .withRange(0, 5);
            request.setProgressCallback(new BosProgressCallback<GetObjectRequest>() {
                @Override
                public void onProgress(GetObjectRequest request, long currentSize, long totalSize) {
                    Log.e(currentSize + "", totalSize + "");
                }
            });
            InputStream input = this.client.getObject(request).getObjectContent();

            Note: The download progress interface is different from the upload progress interface. It is impossible to specify the fragment size for each callback that downloads grow.

          Download Object to the Specified Path

          You can download object directly to the specified path through the following code.

          • Basic procedure

            1.Create an instance of the GetObjectRequest class. 2.Execute the client.getobject ( ). 3.object can be downloaded to the specified path.

          • Sample Code

              // Create a GetObjectRequest. 
              GetObjectRequest getObjectRequest = new GetObjectRequest(<BucketName>,<ObjectKey>); 
                  
              // Download object to file. 
              ObjectMetadata ObjectMetadata = client.getObject(getObjectRequest, new File("/path/to/file","w+")); 

            Note: When the object is downloaded to the specified path using the above method, the method returns the ObjectMetadata object.

          Get the StorageClass of the Object

          The storage class attribute of object is divided into STANDARD (standard storage), STANDARD_IA (low frequency storage), COLD (cold storage) and ARCHIVE (archive storage).

          Sample Code

          public void getObjectStorageClass(){
            //...
          ObjectMetadata meta = client.getObjectMetadata(bucketName, key);
          String storageClass = meta.getStorageClass();
          }

          Get ObjectMetadata Only

          The getObjectMetadata() method can only get the ObjectMetadata rather than the object's entity.

          Sample Code

          ObjectMetadata objectMetadata = client.getObjectMetadata(<BucketName>, <ObjectKey>);

          Get the URL of Object

          You can get the URL of the specified object through the following code. This feature is typically used for scenarios where you temporarily share the URL of an object with other users.

          • Basic procedure

            1.Create an instance of the BOSClient class. 2.Execute BOSClient.generatePresignedUrl( ) method. 3.Return an object URL.

          • Sample Code

              URL url = client.generatePresignedUrl(<BucketName>, <ObjectKey>, <ExpirationInSeconds>);            

            Note: ExpirationInSeconds is the effective duration of the specified URL. It is an optional parameter calculated from the current time. When not configured, the default value of the system is 1,800 seconds. If you want to set the time to be permanent, you can set the ExpirationInSeconds parameter to -1, not to other negative numbers.

          • Complete example

              import java.net.URL;
              import android.app.Activity;
              import android.content.Intent;
              import android.net.Uri;
              import android.os.Bundle;
              import com.baidubce.BceClientException;
              import com.baidubce.BceServiceException;
              import com.baidubce.auth.DefaultBceCredentials;
              import com.baidubce.demo.R;
              import com.baidubce.services.bos.BosClient;
              import com.baidubce.services.bos.BosClientConfiguration;
              
              public class ExampleActivity extends Activity {
              private String bucketName = <BucketName>;
              private String objectKey = <ObjectKey>;
              
              @Override
              protected void onCreate(Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
                  setContentView(R.layout.activity_main);
                  new Thread(new Runnable() {
                      @Override
                      public void run() {
                          try {
                              BosClientConfiguration config = new BosClientConfiguration();
                              config.setCredentials(new DefaultBceCredentials(<AccessKeyID>, <SecretAccessKey>));
                              config.setEndpoint(<EndPoint>);
                              BosClient client = new BosClient(config);
                              
                              //Get the URL of object
                              URL url = client.generatePresignedUrl(<BucketName>, <ObjectKey>, 2000);  
                              Uri uri = Uri.parse(url.toString());
                              Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                              
                              //Execute URL
                              startActivity(intent);
                              
                          } catch (BceServiceException e) {
                              System.out.println("Error ErrorCode: " + e.getErrorCode());
                              System.out.println("Error RequestId: " + e.getRequestId());
                              System.out.println("Error StatusCode: " + e.getStatusCode());
                              System.out.println("Error Message: " + e.getMessage());
                              System.out.println("Error ErrorType: " + e.getErrorType());
                          } catch (BceClientException e) {
                              System.out.println("Error Message: " + e.getMessage());
                          } 
                      }
                  }).start();
              }}

          Delete Object

          • Basic procedure

            1.Create an instance of the BOSClient class. 2.Execute BOSClient.deleteobject() method. 3.If the operation fails, an exception will be thrown. If the operation succeeds, no return value will be returned.

          • Sample Code

              // Delete object. 
              client.deleteObject(<BucketName>,<ObjectKey>);   //Specify the bucket name of the object to be deleted and the object name. 
          • Complete example

              import android.app.Activity;
              import android.os.Bundle;
              import com.baidubce.BceClientException;
              import com.baidubce.BceServiceException;
              import com.baidubce.auth.DefaultBceCredentials;
              import com.baidubce.demo.R;
              import com.baidubce.services.bos.BosClient;
              import com.baidubce.services.bos.BosClientConfiguration;
              
              public class ExampleActivity extends Activity {
              
              private String bucketName = <BucketName>;
              private String objectKey = <ObjectKey>;
              
              @Override
              protected void onCreate(Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
                  setContentView(R.layout.activity_main);
                  new Thread(new Runnable() {
                      @Override
                      public void run() {
                          try {
                              BosClientConfiguration config = new BosClientConfiguration();
                              config.setCredentials(new DefaultBceCredentials(<AccessKeyID>, <SecretAccessKey>));
                              config.setEndpoint(<EndPoint>);
                              BosClient client = new BosClient(config);
                              
                              // Delete Object
                              client.deleteObject(<BucketName>, <ObjectKey>);   //Specify the bucket name of the object to be deleted and the object name
                              
                          } catch (BceServiceException e) {
                              System.out.println("Error ErrorCode: " + e.getErrorCode());
                              System.out.println("Error RequestId: " + e.getRequestId());
                              System.out.println("Error StatusCode: " + e.getStatusCode());
                              System.out.println("Error Message: " + e.getMessage());
                              System.out.println("Error ErrorType: " + e.getErrorType());
                          } catch (BceClientException e) {
                              System.out.println("Error Message: " + e.getMessage());
                          } 
                      }
                  }).start();
              }}

          Copy Object

          Simply Copy Object

          • Basic procedure

            1.Create an instance of the BOSClient class. 2.Execute BOSClient.copyobject( ) method. 3.Return the CopyObjectResponse class instance. You can get the eTag and the last modification time through getETag()/getLastModified().

          • Sample Code

              // Copy Object
              CopyObjectResponse copyObjectResponse = client.copyObject(<SrcBucketName>, <SrcKey>, <DestBucketName>, <DestKey>);  //SrcBucketName, SrcKey is the original address. DestBucketName, DestKey is the address copied to destination
              
              // Print results
              System.out.println("ETag: " + copyObjectResponse.getETag() + " LastModified: " + copyObjectResponse.getLastModified());
          • Complete example

              import android.app.Activity;
              import android.os.Bundle;
              import com.baidubce.BceClientException;
              import com.baidubce.BceServiceException;
              import com.baidubce.auth.DefaultBceCredentials;
              import com.baidubce.demo.R;
              import com.baidubce.services.bos.BosClient;
              import com.baidubce.services.bos.BosClientConfiguration;
              import com.baidubce.services.bos.model.CopyObjectResponse;
              
              public class ExampleActivity extends Activity {
              
              private String srcBucketName = <SrcBucketName>;
              private String srcKey = <SrcKey>;
              
              private String destBucketName = <DestBucketName>;
              private String destKey = <DestKey>;
              
              @Override
              protected void onCreate(Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
                  setContentView(R.layout.activity_main);
                  new Thread(new Runnable() {
                      @Override
                      public void run() {
                          try {
                              BosClientConfiguration config = new BosClientConfiguration();
                              config.setCredentials(new DefaultBceCredentials(<AccessKeyID>, <SecretAccessKey>));
                              config.setEndpoint(<EndPoint>);
                              BosClient client = new BosClient(config);
                              
                              // Copy Object
                              CopyObjectResponse copyObjectResponse = client.copyObject(<SrcBucketName>, <SrcKey>, <DestBucketName>, <DestKey>);
                              
                              // Print results
                              System.out.println("ETag: " + copyObjectResponse.getETag() + " LastModified: " + copyObjectResponse.getLastModified());
                              
                          } catch (BceServiceException e) {
                              System.out.println("Error ErrorCode: " + e.getErrorCode());
                              System.out.println("Error RequestId: " + e.getRequestId());
                              System.out.println("Error StatusCode: " + e.getStatusCode());
                              System.out.println("Error Message: " + e.getMessage());
                              System.out.println("Error ErrorType: " + e.getErrorType());
                          } catch (BceClientException e) {
                              System.out.println("Error Message: " + e.getMessage());
                          } 
                      }
                  }).start();
              }}

            Note: The copyobject method returns a CopyObjectResponse object containing the ETag of the new object and the modification time.

          Copy Object through CopyObjectRequest

          You can also copy object through CopyObjectRequest. This feature is typically used in the following scenarios:

          • Copy an object but reset the meta.
          • Reset the meta of an existing object (set Src and Des to the same object).
          • Basic procedure

            1.Create an instance of the CopyObjectRequest class, introducing into the <SrcBucketName>, <SrcKey>, <DestBucketName> and <DestKey> parameters. 2.Create an instance of ObjectMetadata. 3.Return the CopyObjectResponse class instance. You can get the eTag and the last modification time through getETag()/getLastModified().

          • Sample Code

              //  Create CopyObjectRequest
              CopyObjectRequest copyObjectRequest = new CopyObjectRequest(<SrcBucketName>, <SrcKey>, <DestBucketName>, <DestKey>);
                  
              // Create Metadata
              Map<String, String> userMetadata = new HashMap<String, String>();
              userMetadata.put(<UserMetaKey>,<UserMetaValue>);
              meta.setUserMetadata(userMetadata);
              copyObjectRequest.setNewObjectMetadata(meta);
                  
              // Copy object
              CopyObjectResponse copyObjectResponse = client.copyObject(copyObjectRequest);
                  
              System.out.println("ETag: " + copyObjectResponse.getETag() + " LastModified: " + copyObjectResponse.getLastModified());

            Note: You can modify the objectMeta of object through CopyObjectRequest and set MatchingETagConstraints parameters.

          Multipart Upload of Object

          Multipart Upload Scenario

          In addition to uploading files to BOS through putObject () method, BOS also provides another upload mode: Multipart Upload. You can use the Multipart Upload mode in the following application scenarios (but not limited to this), such as:

          • Breakpoint upload support is required.
          • The file to upload is larger than 5 GB.
          • The network conditions are poor, and the connection with BOS servers is often disconnected.
          • The file needs to be uploaded streaming.
          • The size of the uploaded file cannot be determined before uploading it.

          Multipart Upload Process

          Suppose you have a file with the local path of /path/to/file.zip , upload it through Multipart Upload to BOS for its large size.

          • Basic procedure

            1.Initialize Multipart Upload. 2.Upload in parts. 3.Complete Multipart Upload.

          Initialize Multipart Upload.

          Use the initiateMultipartUpload method to initialize a Multipart Upload event:

          • Sample Code

              // Start Multipart Upload
              InitiateMultipartUploadRequest initiateMultipartUploadRequest =
                    new InitiateMultipartUploadRequest(<BucketName>, <ObjectKey>);
              InitiateMultipartUploadResponse initiateMultipartUploadResponse =
                    client.initiateMultipartUpload(initiateMultipartUploadRequest);
              
              // Print UploadId
              System.out.println("UploadId: " + initiateMultipartUploadResponse.getUploadId());

            Note: The returned result of initiateMultipartUpload contains UploadId . It is the unique identification to distinguish the Multipart Upload events. We will use it in later operations.

          Upload in Parts

          Upload files in parts.

          • Sample Code

              // Set each part to 5 MB. 
              final long partSize = 1024 * 1024 * 5L; 
                  
              File partFile = new File("/path/to/file.zip"); 
                  
              // Calculate the number of part. 
              int partCount = (int) (partFile.length() / partSize); 
              if (partFile.length() % partSize != 0) { 
                  partCount++; 
              } 
              // Create a List to save the ETag and PartNumber uploaded in parts. 
              List<PartETag> partETags = new ArrayList<PartETag>(); 
              // Get file stream. 
              FileInputStream fis = new FileInputStream(partFile); 
              for (int i = 0; i< partCount; i++) { 
                                      
                  // Calculate the size of each part. 
                  long skipBytes = partSize * i; 
                  long size = partSize< partFile.length() - skipBytes ? 
                            partSize : partFile.length() - skipBytes; 
              
                  byte[] buf = new byte[(int)size]; 
                  int offset = 0; 
                  while (true) { 
                      int byteRead = fis.read(buf, offset, (int)size); 
                      offset += byteRead; 
                      if (byteRead< 0| |  offset >= size) { 
                         break; 
                      } 
                  } 
                  ByteArrayInputStream bufStream = new ByteArrayInputStream(buf); 
              
                  // Create UploadPartRequest, and upload part. 
                  UploadPartRequest uploadPartRequest = new UploadPartRequest(); 
                  uploadPartRequest.setBucketName(bucketName); 
                  uploadPartRequest.setKey(objectkey); 
                  uploadPartRequest.setUploadId(initiateMultipartUploadResponse.getUploadId()); 
                  uploadPartRequest.setInputStream(bufStream); 
                  uploadPartRequest.setPartSize(size); 
                  uploadPartRequest.setPartNumber(i + 1); 
                  // Upload progress callback. 
              	 uploadPartRequest.setProgressCallback(new BosProgressCallback<UploadPartRequest>() { 
                  	 @Override 
                  	 public void onProgress(UploadPartRequest request, long currentSize, long totalSize) { 
                      	 Log.e(currentSize + "", totalSize + ""); 
                  	 } 
              	 }); 
                  
                  UploadPartResponse uploadPartResponse = client.uploadPart(uploadPartRequest); 
              
                  // Save the returned PartETag to the List. 
                  partETags.add(uploadPartResponse.getPartETag()); 
              
                  System.out.println(uploadPartResponse.getPartETag()); 
                } 
                // Close the file. 
                fis.close(); 

            Note: The core of the above code is to call the UploadPart method to upload each part. Pay attention to the following points:

            • The UploadPart method requires that all but the last Part be larger than or equal to 5 MB. However, the Upload Part interface does not immediately verify the size of the Upload Part. It verifies only in case of Complete Multipart Upload.
            • To ensure no error occurs to data in the network transmission process, it is recommended that you use the Content-MD5 value returned by each part BOS to verify the correctness of the uploaded part data respectively after UploadPart. When all part data is combined into one object, it no longer contains the MD5 value.
            • Part numbers range from 1 to 10,000. If this range is exceeded, BOS will return the error code of InvalidArgument.
            • Every time you upload a Part, locate the stream to the location corresponding to the beginning of the uploaded part.
            • Every time a Part is uploaded, the returned result of BOS will contain a PartETag object. It is a combination of the Etag and the PartNumber of the uploaded part. It will be used in the next steps to complete Multipart Upload, so it needs to be saved. In general, these PartETag objects will be saved to the List.
            • The use of the progress callback interface can be referred to in the "Get Upload Progress" chapter.

          Complete Multipart Upload

          • Sample Code

              CompleteMultipartUploadRequest completeMultipartUploadRequest = 
                    new CompleteMultipartUploadRequest(<BucketName>,<ObjectKey>, initiateMultipartUploadResponse.getUploadId(), partETags); 
              
              // Complete Multipart Upload. 
              CompleteMultipartUploadResponse completeMultipartUploadResponse = 
                    client.completeMultipartUpload(completeMultipartUploadRequest); 
              
              // Print the ETag of object. 
              System.out.println(completeMultipartUploadResponse.getETag()); 

            Note: The partETags in the above code is the list of partETag saved in the Step 2.BOS will verify the validity of each data Part one by one after receiving the Part list submitted by the user. When all data Parts are verified, BOS will combine these data parts into a complete object.

          • Complete example

              import java.io.File; 
              import java.io.FileInputStream; 
              import java.io.IOException; 
              import java.util.ArrayList; 
              import java.util.List; 
              import org.json.JSONException; 
              import android.app.Activity; 
              import android.os.Bundle; 
              import com.baidubce.BceClientException; 
              import com.baidubce.BceServiceException; 
              import com.baidubce.auth.DefaultBceCredentials; 
              import com.baidubce.demo.R; 
              import com.baidubce.services.bos.BosClient; 
              import com.baidubce.services.bos.BosClientConfiguration; 
              import com.baidubce.services.bos.model.CompleteMultipartUploadRequest; 
              import com.baidubce.services.bos.model.CompleteMultipartUploadResponse; 
              import com.baidubce.services.bos.model.InitiateMultipartUploadRequest; 
              import com.baidubce.services.bos.model.InitiateMultipartUploadResponse; 
              import com.baidubce.services.bos.model.PartETag; 
              import com.baidubce.services.bos.model.UploadPartRequest; 
              import com.baidubce.services.bos.model.UploadPartResponse; 
              
              public class ExampleActivity extends Activity { 
              
              private String bucketName = <BucketName>;
              private String objectKey = <ObjectKey>;
                  
              @Override 
              protected void onCreate(Bundle savedInstanceState) { 
                  super.onCreate(savedInstanceState); 
                  setContentView(R.layout.activity_main); 
                  new Thread(new Runnable() { 
                      @Override 
                      public void run() { 
                          try { 
                            BosClientConfiguration config = new BosClientConfiguration(); 
                            config.setCredentials(new DefaultBceCredentials(<AccessKeyID>,<SecretAccessKey>)); 
                            config.setEndpoint(<EndPoint>); 
                            BosClient client = new BosClient(config); 
                              
                            // Start Multipart Upload. 
                            InitiateMultipartUploadRequest initiateMultipartUploadRequest = new InitiateMultipartUploadRequest(<BucketName>,<ObjectKey>); 
                            InitiateMultipartUploadResponse initiateMultipartUploadResponse = 
                                      client.initiateMultipartUpload(initiateMultipartUploadRequest); 
              
                            // Print UploadId. 
                            System.out.println("UploadId: " + initiateMultipartUploadResponse.getUploadId()); 
                              
                            // Set each part to 5 MB. 
                            final long partSize = 1024 * 1024 * 5L; 
              
                            File partFile = new File("/path/to/file.zip"); 
              
                            // Calculate the number of part. 
                            int partCount = (int) (partFile.length() / partSize); 
                            if (partFile.length() % partSize != 0) { 
                                partCount++; 
                            } 
              
                            // Create a List to save the ETag and PartNumber uploaded in parts. 
                            List<PartETag> partETags = new ArrayList<PartETag>(); 
              
                            // Get file stream. 
                            FileInputStream fis = new FileInputStream(partFile); 
                            for (int i = 0; i< partCount; i++) {                       
              
                                // Calculate the size of each part. 
                                long skipBytes = partSize * i; 
                                long size = partSize< partFile.length() - skipBytes ? 
                                        partSize : partFile.length() - skipBytes; 
              
                                byte[] buf = new byte[(int)size]; 
                                int offset = 0; 
                                while (true) { 
                                    int byteRead = fis.read(buf, offset, (int)size); 
                                    offset += byteRead; 
                                    if (byteRead< 0| |  offset >= size) { 
                                        break; 
                                    } 
                                } 
                                ByteArrayInputStream bufStream = new ByteArrayInputStream(buf); 
              
                                // Create UploadPartRequest, and upload part. 
                                UploadPartRequest uploadPartRequest = new UploadPartRequest(); 
                                uploadPartRequest.setBucketName(<BucketName>); 
                                uploadPartRequest.setKey(<ObjectKey>); 
                                uploadPartRequest.setUploadId(initiateMultipartUploadResponse.getUploadId()); 
                                uploadPartRequest.setInputStream(fis); 
                                uploadPartRequest.setPartSize(size); 
                                uploadPartRequest.setPartNumber(i + 1); 
                                UploadPartResponse uploadPartResponse = client.uploadPart(uploadPartRequest); 
              
                                // Save the returned PartETag to the List. 
                                partETags.add(uploadPartResponse.getPartETag()); 
                                 
                                System.out.println(uploadPartResponse.getPartETag());                                         
                            } 
                            // Close the file 
                            fis.close(); 
                              
                            CompleteMultipartUploadRequest completeMultipartUploadRequest = new CompleteMultipartUploadRequest(<BucketName>,<ObjectKey>, initiateMultipartUploadResponse.getUploadId(), partETags); 
              
                            // Complete Multipart Upload. 
                            CompleteMultipartUploadResponse completeMultipartUploadResponse = 
                                    client.completeMultipartUpload(completeMultipartUploadRequest); 
              
                            // Print the ETag of object. 
                            System.out.println(completeMultipartUploadResponse.getETag()); 
                              
                          } catch (BceServiceException e) { 
                              System.out.println("Error ErrorCode: " + e.getErrorCode()); 
                              System.out.println("Error RequestId: " + e.getRequestId()); 
                              System.out.println("Error StatusCode: " + e.getStatusCode()); 
                              System.out.println("Error Message: " + e.getMessage()); 
                              System.out.println("Error ErrorType: " + e.getErrorType()); 
                          } catch (BceClientException e) { 
                              System.out.println("Error Message: " + e.getMessage()); 
                          } catch (IOException e) { 
                              // TODO Auto-generated catch block 
                              e.printStackTrace(); 
                          } catch (JSONException e) { 
                              // TODO Auto-generated catch block 
                              e.printStackTrace(); 
                          } 
                      } 
                  }).start(); 
              }} 

          Cancel Multipart Upload

          You can use the abortMultipartUpload method to cancel Multipart Upload.

          • Sample Code

              AbortMultipartUploadRequest abortMultipartUploadRequest = 
                  new AbortMultipartUploadRequest(<BucketName>,<ObjectKey>,<UploadId>); 
              
              // Cancel Multipart Upload. 
              client.abortMultipartUpload(abortMultipartUploadRequest); 

          Get Unfinished Multipart Upload

          You can use the listMultipartUploads method to get unfinished Multipart Upload events in the bucket.

          • Basic procedure

            1.Create an instance of the listMultipartUploadsRequest class, introducing into the <BucketName> parameter. 2.Create an instance of the BOSClient class and execute the BOSClient.listMultipartUploads( ) method. 3.istMultipartUploads() returns information about uploaded parts.

          • Sample Code

              ListMultipartUploadsRequest listMultipartUploadsRequest = 
                  new ListMultipartUploadsRequest(<BucketName>); 
              
              // Get all upload events in the bucket. 
              ListMultipartUploadsResponse list = client.listMultipartUploads(listMultipartUploadsRequest); 
                  
              // Traverse all uploaded events. 
              for (MultipartUploadSummary multipartUpload : list.getMultipartUploads()) { 
                  System.out.println("Key: " + multipartUpload.getKey() + " UploadId: " + multipartUpload.getUploadId()); 
              } 

            Note:

            • By default, only 1,000 objects are returned and the IsTruncated value is True if the number of Multipart Upload events in bucket is over 1,000. Besides, NextKeyMarker is returned as the starting point for the next reading.
            • For more Multipart Upload events, you can use the KeyMarker parameter to read them by several times.
          • Complete example

              import android.app.Activity;
              import android.os.Bundle;
              import com.baidubce.BceClientException;
              import com.baidubce.BceServiceException;
              import com.baidubce.auth.DefaultBceCredentials;
              import com.baidubce.demo.R;
              import com.baidubce.services.bos.BosClient;
              import com.baidubce.services.bos.BosClientConfiguration;
              import com.baidubce.services.bos.model.ListMultipartUploadsRequest;
              import com.baidubce.services.bos.model.ListMultipartUploadsResponse;
              import com.baidubce.services.bos.model.MultipartUploadSummary;
              
              public class ExampleActivity extends Activity {
              
              private String bucketName = <BucketName>;
              
              @Override
              protected void onCreate(Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
                  setContentView(R.layout.activity_main);
                  new Thread(new Runnable() {
                      @Override
                      public void run() {
                          try {
                              BosClientConfiguration config = new BosClientConfiguration();
                              config.setCredentials(new DefaultBceCredentials(<AccessKeyID>, <SecretAccessKey>));
                              config.setEndpoint(<EndPoint>);
                              BosClient client = new BosClient(config);
                              
                              ListMultipartUploadsRequest listMultipartUploadsRequest = 
                                      new ListMultipartUploadsRequest(<BucketName>);
              
                                  // Get all upload events in the bucket
                              ListMultipartUploadsResponse listing = client.listMultipartUploads(listMultipartUploadsRequest);
                              
                               // Traverse all uploaded events
                               for (MultipartUploadSummary multipartUpload : listing.getMultipartUploads()) {
                                   System.out.println("Key: " + multipartUpload.getKey() + " UploadId: " + multipartUpload.getUploadId());
                               }
                              
                          } catch (BceServiceException e) {
                              System.out.println("Error ErrorCode: " + e.getErrorCode());
                              System.out.println("Error RequestId: " + e.getRequestId());
                              System.out.println("Error StatusCode: " + e.getStatusCode());
                              System.out.println("Error ErrorType: " + e.getErrorType());
                              System.out.println("Error Message: " + e.getMessage());
                          } catch (BceClientException e) {
                              System.out.println("Error Message: " + e.getMessage());
                          } 
                      }
                  }).start();
              }}

          Get All Uploaded Part Information

          You can use the listParts method to get all uploaded parts in an uploaded event.

          • Basic procedure

            1.Create an instance of the ListPartsRequest class, introducing into <BucketName>, <ObjectKey> and <UploadId> parameters. 2.Create an instance of the BOSClient class and execute the BOSClient.listParts ( ) method. 3.listParts () returns information about all uploaded parts.

          • Sample Code

              ListPartsRequest listPartsRequest = new ListPartsRequest(<BucketName>,<ObjectKey>,<UploadId>);  
              
              // Get information about all uploaded Parts. 
              ListPartsResponse partListing = client.listParts(listPartsRequest);   
              
              // Traverse all Parts. 
              for (PartSummary part : partListing.getParts()) { 
                  System.out.println("PartNumber: " + part.getPartNumber() + " ETag: " + part.getETag()); 
              } 

            Note:

            • By default, only 1,000 objects are returned and the IsTruncated value is True if the number of Multipart Upload events in bucket is over 1,000. Besides, NextPartNumberMarker is returned as the starting point for the next reading.
            • For more uploaded part information, you can use the PartNumberMarker parameter to read it by several times.
          • Complete example

              import android.app.Activity;
              import android.os.Bundle;
              import com.baidubce.BceClientException;
              import com.baidubce.BceServiceException;
              import com.baidubce.auth.DefaultBceCredentials;
              import com.baidubce.demo.R;
              import com.baidubce.services.bos.BosClient;
              import com.baidubce.services.bos.BosClientConfiguration;
              import com.baidubce.services.bos.model.ListPartsRequest;
              import com.baidubce.services.bos.model.ListPartsResponse;
              import com.baidubce.services.bos.model.PartSummary;
              
              public class ExampleActivity extends Activity {
              
              private String bucketName = <BucketName>;
              private String objectKey = <ObjectKey>;
              private String uploadId = <UploadId>;
              
              @Override
              protected void onCreate(Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
                  setContentView(R.layout.activity_main);
                  new Thread(new Runnable() {
                      @Override
                      public void run() {
                          try {
                              BosClientConfiguration config = new BosClientConfiguration();
                              config.setCredentials(new DefaultBceCredentials(<AccessKeyID>, <SecretAccessKey>));
                              config.setEndpoint(<EndPoint>);
                              BosClient client = new BosClient(config);
                              
                              ListPartsRequest listPartsRequest = new ListPartsRequest(<BucketName>, <ObjectKey>, <UploadId>);
                              listPartsRequest.setMaxParts(100);
                              listPartsRequest.setPartNumberMarker(50);
                              
                               // Get information about all uploaded Parts
                               ListPartsResponse partListing = client.listParts(listPartsRequest);
                                   
                               // Traverse all Parts
                               for (PartSummary part : partListing.getParts()) {
                                   System.out.println("PartNumber: " + part.getPartNumber() + " ETag: " + part.getETag());
                               }
                              
                          } catch (BceServiceException e) {
                              System.out.println("Error ErrorCode: " + e.getErrorCode());
                              System.out.println("Error RequestId: " + e.getRequestId());
                              System.out.println("Error StatusCode: " + e.getStatusCode());
                              System.out.println("Error ErrorType: " + e.getErrorType());
                              System.out.println("Error Message: " + e.getMessage());
                          } catch (BceClientException e) {
                              System.out.println("Error Message: " + e.getMessage());
                          } 
                      }
                  }).start();
              }}
          Previous
          Bucket Management
          Next
          Log