Upload Object
Simplest upload
Basic workflow
- Instantiate the BOSClient class.
- The BOSClient.putObject() method allows objects to be uploaded in four ways: file, data stream, binary string, and plain string.
- For the returned PutObjectResponse instance, call getETag() to get the successfully uploaded ETag.
Example code
1// Get specified file
2 File file = new File(<FilePath>); //Specify the file path
3 // Upload object as a file
4PutObjectResponse putObjectFromFileResponse =
5 client.putObject(<BucketName>, <ObjectKey>, file);
6 // Obtain data stream
7InputStream inputStream = new FileInputStream(<FilePath>);
8 // Upload an object in the form of a data stream
9PutObjectResponse putObjectResponseFromInputStream =
10 client.putObject(<BucketName>, <ObjectKey>, inputStream);
11 // Upload object as binary string
12PutObjectResponse putObjectResponseFromByte =
13 client.putObject(<BucketName>, <ObjectKey>, <byte>);
14 // Upload object in string form
15PutObjectResponse putObjectResponseFromString =
16 client.putObject(<BucketName>, <ObjectKey>, <string>);
17 // Print ETag
18System.out.println(putObjectFromFileResponse.getETag());
Note: Objects are uploaded to BOS as files, and the putObject function supports uploading objects with a size not exceeding 5GB. After the putObject request is processed successfully, BOS will return the ETag of the object in the Header as the file identifier.
Complete example
1import java.io.File;
2import java.io.FileInputStream;
3import java.io.FileNotFoundException;
4import java.io.InputStream;
5import android.app.Activity;
6import android.os.Bundle;
7import com.baidubce.BceClientException;
8import com.baidubce.BceServiceException;
9import com.baidubce.auth.DefaultBceCredentials;
10import com.baidubce.development.R;
11import com.baidubce.services.bos.BosClient;
12import com.baidubce.services.bos.BosClientConfiguration;
13import com.baidubce.services.bos.model.PutObjectResponse;
14
15public class ExampleActivity extends Activity {
16 private String bucketName = <BucketName>;
17 private String objectKey = <ObjectKey>;
18 byte[] b = null;
19 String str = <PutString>;
20 @Override
21 protected void onCreate(Bundle savedInstanceState) {
22 super.onCreate(savedInstanceState);
23 setContentView(R.layout.activity_main);
24 new Thread(new Runnable() {
25 @Override
26 public void run() {
27 try {
28 BosClientConfiguration config = new BosClientConfiguration();
29 config.setCredentials(new DefaultBceCredentials(<AccessKeyID>, <SecretAccessKey>));
30 config.setEndpoint(<EndPoint>);
31 BosClient client = new BosClient(config);
32 // Get specified file
33 File file = new File("/path/to/file.zip");
34 // Upload object as a file
35 PutObjectResponse putObjectFromFileResponse = client.putObject(<BucketName>, <ObjectKey>, file);
36 // Obtain data stream
37 InputStream inputStream = new FileInputStream("/path/to/test.zip");
38 // Upload an object in the form of a data stream
39 PutObjectResponse putObjectResponseFromInputStream = client.putObject(<BucketName>, <ObjectKey>, inputStream);
40 // Upload object as binary string
41 PutObjectResponse putObjectResponseFromByte = client.putObject(<BucketName>, <ObjectKey>, b);
42 // Upload object in string form
43 PutObjectResponse putObjectResponseFromString = client.putObject(<BucketName>, <ObjectKey>, str);
44 // Print ETag
45 System.out.println(putObjectFromFileResponse.getETag());
46 } catch (BceServiceException e) {
47 System.out.println("Error ErrorCode: " + e.getErrorCode());
48 System.out.println("Error RequestId: " + e.getRequestId());
49 System.out.println("Error StatusCode: " + e.getStatusCode());
50 System.out.println("Error Message: " + e.getMessage());
51 System.out.println("Error ErrorType: " + e.getErrorType());
52 } catch (BceClientException e) {
53 System.out.println("Error Message: " + e.getMessage());
54 } catch (FileNotFoundException e) {
55 // TODO Auto-generated catch block
56 e.printStackTrace();
57 }
58 }
59 }).start();
60}}
Set the Copy attributes of an object
The CopyObject API copies an existing object to a new one. During the process, it checks the source object's ETag or modification status to decide whether to proceed with the operation. The detailed parameters are as follows:
| Name | Types | Description | Whether required |
|---|---|---|---|
| x-bce-copy-source-if-match | String | If the ETag value of the source object matches the ETag value provided by the user, the copy operation is performed; otherwise, it fails. | No |
| x-bce-copy-source-if-none-match | String | If the ETag value of the source object does not match the ETag value provided by the user, the copy operation is performed; otherwise, it fails. | No |
| x-bce-copy-source-if-unmodified-since | String | If the source object has not been modified since x-bce-copy-source-if-unmodified-since, the copy operation will proceed; otherwise, it will fail. | No |
| x-bce-copy-source-if-modified-since | String | If the source object has been modified since x-bce-copy-source-if-modified-since, the copy operation will proceed; otherwise, it will fail. | No |
Example code
1// Initialize BosClient
2BosClient client = ...;
3 // Create CopyObjectRequest object
4CopyObjectRequest copyObjectRequest = new CopyObjectRequest(srcBucketName, srcKey, destBucketName, destKey);
5 // Set new Metadata
6Map<String, String> userMetadata = new HashMap<String, String>();
7userMetadata.put("<user-meta-key>","<user-meta-value>");
8ObjectMetadata meta = new ObjectMetadata();
9meta.setUserMetadata(userMetadata);
10copyObjectRequest.setNewObjectMetadata(meta);
11//copy-source-if-match
12copyObjectRequest.withETag("111111111183bf192b57a4afc76fa632");
13//copy-source-if-none-match
14copyObjectRequest.withNoMatchingETagConstraint("111111111183bf192b57a4afc76fa632");
15Date modifiedSinceConstraint = new Date();
16SimpleDateFormat df = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z", Locale.UK);
17df.setTimeZone(new java.util.SimpleTimeZone(0, "GMT"));
18String date = df.format(modifiedSinceConstraint);
19//copy-source-if-modified-since
20copyObjectRequest.withModifiedSinceConstraint(date);
21//copy-source-if-unmodified-since
22copyObjectRequest.withUnmodifiedSinceConstraint(date);
23 // Copy Object
24CopyObjectResponse copyObjectResponse = client.copyObject(copyObjectRequest);
Set object's HTTP Header
BOS allows setting Http Headers when uploading an object.
Basic workflow
- Create an ObjectMetadata instance.
- Use methods like setContentLength() and setContentType() to configure Http Headers.
- Pass the metadata as a parameter when calling client.putObject().
Example code
1// Create an instance of the ObjectMetadata class
2ObjectMetadata meta = new ObjectMetadata();
3 // Set ContentLength size
4meta.setContentLength(<Length>);
5 // Set ContentType
6meta.setContentType("application/json");
7client.putObject(<BucketName>, <ObjectKey>, content, meta);
Note: Headers can be set with attributes such as "Cache-Control", "Content-Encoding", "Content-Disposition", and "Expires"
Complete example
1import java.io.FileInputStream;
2import java.io.FileNotFoundException;
3import java.io.InputStream;
4import android.app.Activity;
5import android.os.Bundle;
6import com.baidubce.BceClientException;
7import com.baidubce.BceServiceException;
8import com.baidubce.auth.DefaultBceCredentials;
9import com.baidubce.demo.R;
10import com.baidubce.services.bos.BosClient;
11import com.baidubce.services.bos.BosClientConfiguration;
12import com.baidubce.services.bos.model.ObjectMetadata;
13import com.baidubce.services.bos.model.PutObjectResponse;
14public class ExampleActivity extends Activity {
15private String bucketName = <BucketName>;
16private String objectKey = <ObjectKey>;
17@Override
18protected void onCreate(Bundle savedInstanceState) {
19 super.onCreate(savedInstanceState);
20 setContentView(R.layout.activity_main);
21 new Thread(new Runnable() {
22 @Override
23 public void run() {
24 try {
25 BosClientConfiguration config = new BosClientConfiguration();
26 config.setCredentials(new DefaultBceCredentials(<AccessKeyID>, <SecretAccessKey>));
27 config.setEndpoint(<EndPoint>);
28 BosClient client = new BosClient(config);
29 // Obtain data stream
30 InputStream inputStream = new FileInputStream("/path/to/test.zip");
31 // Create an instance of the ObjectMetadata class
32 ObjectMetadata meta = new ObjectMetadata();
33 // Set ContentLength size
34 meta.setContentLength(1000);
35 // Set ContentType
36 meta.setContentType("application/json");
37 PutObjectResponse putObjectResponseFromInputStream = client.putObject(bucketName, objectKey, inputStream, meta);
38 // Print ETag
39 System.out.println(putObjectResponseFromInputStream.getETag());
40 } catch (BceServiceException e) {
41 System.out.println("Error ErrorCode: " + e.getErrorCode());
42 System.out.println("Error RequestId: " + e.getRequestId());
43 System.out.println("Error StatusCode: " + e.getStatusCode());
44 System.out.println("Error Message: " + e.getMessage());
45 System.out.println("Error ErrorType: " + e.getErrorType());
46 } catch (BceClientException e) {
47 System.out.println("Error Message: " + e.getMessage());
48 } catch (FileNotFoundException e) {
49 // TODO Auto-generated catch block
50 e.printStackTrace();
51 }
52 }
53 }).start();
54}}
User-defined metadata
BOS supports user-defined metadata for object descriptions.
Basic workflow
- Create an ObjectMetadata instance.
- Use the addUserMetadata() method to add custom metadata to the Http Headers.
- Pass the metadata as a parameter when calling client.putObject().
Example code
1// Set the value of custom metadata name to my-data
2meta.addUserMetadata("name", "my-data");
3 // Upload Object
4client.putObject(<BucketName>, <ObjectKey>, <Content>, meta);
Note: In the provided example, a user-defined metadata property is created with the key "name" and the value "my-data." This metadata can be retrieved when the object is downloaded. Though multiple such parameters can be added, the combined size of all User Metadata must not exceed 2KB.
Complete example
1import java.io.FileInputStream;
2import java.io.FileNotFoundException;
3import java.io.InputStream;
4import android.app.Activity;
5import android.os.Bundle;
6import com.baidubce.BceClientException;
7import com.baidubce.BceServiceException;
8import com.baidubce.auth.DefaultBceCredentials;
9import com.baidubce.demo.R;
10import com.baidubce.services.bos.BosClient;
11import com.baidubce.services.bos.BosClientConfiguration;
12import com.baidubce.services.bos.model.ObjectMetadata;
13import com.baidubce.services.bos.model.PutObjectResponse;
14public class ExampleActivity extends Activity {
15private String bucketName = <BucketName>;
16private String objectKey = <ObjectKey>;
17@Override
18protected void onCreate(Bundle savedInstanceState) {
19 super.onCreate(savedInstanceState);
20 setContentView(R.layout.activity_main);
21 new Thread(new Runnable() {
22 @Override
23 public void run() {
24 try {
25 BosClientConfiguration config = new BosClientConfiguration();
26 config.setCredentials(new DefaultBceCredentials(<AccessKeyID>, <SecretAccessKey>));
27 config.setEndpoint(<EndPoint>);
28 BosClient client = new BosClient(config);
29 // Obtain data stream
30 InputStream inputStream = new FileInputStream("/path/to/test.zip");
31 // Create an instance of the ObjectMetadata class
32 ObjectMetadata meta = new ObjectMetadata();
33 // Custom metadata
34 meta.addUserMetadata("name", "my-data");
35 PutObjectResponse putObjectResponseFromInputStream = client.putObject(<BucketName>, <ObjectKey>, inputStream, meta);
36 // Print ETag
37 System.out.println(putObjectResponseFromInputStream.getETag());
38 } catch (BceServiceException e) {
39 System.out.println("Error ErrorCode: " + e.getErrorCode());
40 System.out.println("Error RequestId: " + e.getRequestId());
41 System.out.println("Error StatusCode: " + e.getStatusCode());
42 System.out.println("Error Message: " + e.getMessage());
43 System.out.println("Error ErrorType: " + e.getErrorType());
44 } catch (BceClientException e) {
45 System.out.println("Error Message: " + e.getMessage());
46 } catch (FileNotFoundException e) {
47 // TODO Auto-generated catch block
48 e.printStackTrace();
49 }
50 }
51 }).start();
52}}
Upload object in append mode
BOS provides an AppendObject feature for uploading files in append mode, making it ideal for scenarios like log appending, live streaming, and real-time video uploads. Objects created via AppendObject belong to the Appendable Objects category, allowing additional data to be appended. In contrast, objects uploaded using PutObject are classified as Normal Objects and do not support data appending. An AppendObject has a size limit between 0 and 5GB.
Example code
1public void AppendObject(BosClient client, String bucketName, String objectKey, byte[] byte1, String string1) {
2 // Get specified file
3 File file = new File("/path/to/file.zip");
4 // Obtain data stream
5 InputStream inputStream = new FileInputStream("/path/to/test.zip");
6 // Upload object as a file
7 AppendObjectResponse appendObjectFromFileResponse = client.appendObject(bucketName, objectKey, file);
8 // Upload an object in the form of a data stream
9 AppendObjectResponse appendObjectResponseFromInputStream = client.appendObject(bucketName, objectKey, inputStream);
10 // Upload object as binary string
11 AppendObjectResponse appendObjectResponseFromByte = client.appendObject(bucketName, objectKey, byte1);
12 // Upload object in string form
13 AppendObjectResponse appendObjectResponseFromString = client.appendObject(bucketName, objectKey, string1);
14 // Append content to AppendFile
15 Long nextOffset = appendObjectFromFileResponse.getNextAppendOffset();
16 AppendObjectRequest request =new AppendObjectRequest(bucketName, objectKey,
17 RestartableInputStream.wrap(string1.getBytes()));
18 request.withOffset(nextOffset);
19 AppendObjectResponse appendResponse = client.appendObject(request);
20}
Obtain upload progress
The Android SDK supports providing real-time upload progress information during the upload. It currently supports four APIs: PutObject, AppendObject, UploadPart and PutSuperObjectFromFile Using the progress upload interface requires constructing the corresponding Request (PutObjectRequest, AppendObjectRequest, UploadPartRequest and PutSuperObjectRequest).
The SDK offers an upload progress callback API that enables you to define operations to execute during uploads, such as updating the UI.
1public interface BceProgressCallback<T extends AbstractBceRequest> {
2 // request is the upload request
3 // currentSize is the current upload size (unit: byte)
4 // totalSize is the total size to be uploaded in this request (unit: byte)
5 void onProgress(T request, long currentSize, long totalSize);
6}
PutObject example code
1PutObjectRequest request = new PutObjectRequest(this.bucketName, "test", file);
2ObjectMetadata objectMetadata = new ObjectMetadata();
3objectMetadata.setContentType("text/plain");
4request.setObjectMetadata(objectMetadata);
5request.setProgressCallback(new BosProgressCallback<PutObjectRequest>() {
6 @Override
7 public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
8 Log.e(currentSize + "", totalSize + "");
9 }
10});
11String eTag = this.client.putObject(request).getETag();
AppendObject example code
1ObjectMetadata objectMetadata = new ObjectMetadata();
2objectMetadata.setContentType("text/plain");
3AppendObjectRequest request = new AppendObjectRequest(this.bucketName, "test", file);
4request.setObjectMetadata(objectMetadata);
5AppendObjectResponse response = this.client.appendObject(request);
6Long nextOffset = response.getNextAppendOffset();
7request.withOffset(nextOffset);
8request.setProgressCallback(new BosProgressCallback<AppendObjectRequest>() {
9 @Override
10 public void onProgress(AppendObjectRequest request, long currentSize, long totalSize) {
11 Log.e(currentSize + "", totalSize + "");
12 }
13});
14response = this.client.appendObject(request);
UploadPart example code
1UploadPartRequest request = new UploadPartRequest().withBucketName(this.bucketName)
2 .withKey("test").withUploadId(uploadId).withPartNumber(1).withPartSize(8000)
3 .withInputStream(fis);
4request.setProgressCallback(new BosProgressCallback<UploadPartRequest>() {
5 @Override
6 public void onProgress(UploadPartRequest request, long currentSize, long totalSize) {
7 Log.e(currentSize + "", totalSize + "");
8 }
9});
10UploadPartResponse response = this.client.uploadPart(request);
PutSuperObjectFromFile example code
1PutSuperObjectRequest request = new PutSuperObjectRequest().withBucketName(this.bucketName)
2 .withKey("test").withPartSize(1024*1024*2L).withFile(file);
3request.setProgressCallback(new BosProgressCallback<PutSuperObjectRequest>() {
4 @Override
5 public void onProgress(PutSuperObjectRequest request, long currentSize, long totalSize) {
6 Log.e(currentSize + "", totalSize + "");
7 }
8});
9PutSuperObjectResponse response = this.client.putSuperObjectFromFile(request);
By default, the SDK’s upload progress callback granularity is 2,048 bytes. You can adjust the granularity to better suit your application using the provided methods.
BosClientConfiguration config=new BosClientConfiguration(); config.setUploadSegmentPart(1024);
Note: This value must be between 1-8192. If outside this range, Android SDK will forcibly set it to 2048.
Cancellation interface
Android SDK supports canceling this request during the request process. The remaining data in the upload request will not be uploaded to BOS. Canceling the operation in the download request will close the connection, and the executing operation will throw Request is canceled! exception.
All BOS operations support cancellation interfaces, but completed requests cannot be canceled, and no exceptions will be thrown for completed operations
1// Take the upload interface cancellation as an example
2final PutObjectRequest req = new PutObjectRequest(<BucketName>, <ObjectName>,
3 new FileInputStream(<FilePath>));
4Runnable cancelTask = new Runnable() {
5 @Override
6 public void run() {
7 try {
8 Thread.sleep(100);
9 } catch (InterruptedException e) {
10 e.printStackTrace()
11 }
12 // Cancel the current upload request
13 req.cancel();
14 }
15};
16new Thread(cancelTask).start();
17client.putObject(req);
Synchronous callback
The Android SDK supports the BOS server-side synchronous callback API. By setting the process parameter in the PutObjectRequest, the BOS server can actively trigger the callback API after upload completion to notify the client.
1PutObjectRequest request = new PutObjectRequest({bucket}, {object}, {inputStream});
2 // Set the x-bce-process parameter
3request.setProcess({x-bce-process});
4PutObjectResponse response = client.putObject(request);
5 // Obtain the returned http status code
6int statusCode = response.getHttpResponse().getStatusCode();
7 // Obtain the data returned by the callback API
8string callbackString = response.getServerCallbackReturnBody();
Single-link rate limit
Baidu AI Cloud Object Storage (BOS) applies bandwidth limits per bucket. When the user's upload or download bandwidth usage reaches the threshold, the error code RequestRateLimitExceeded will be triggered.
To ensure normal service usage, BOS implements traffic control during upload and download processes, ensuring that large traffic services do not impact other applications.
The read-write API supports setting the specified rate limit value. The value range of the rate limit value is 819200~838860800 in bit/s, that is, 100KB/s~100MB/s. The rate limit value must be a number. BOS will limit the rate of this request according to the specified rate limit value. When the rate limit value is not within this range or is illegal, it will return the error code 400.
Currently, PutObjectRequest, PutSuperObjectRequest, UploadPartRequest, CopyObjectRequest and GetObjectRequest all support setting single-link rate limits. Take PutObjectRequest as an example:
1PutObjectRequest request = new PutObjectRequest({bucket}, {object}, {inputStream});
2 // Set single-link rate limit
3request.setTrafficLimitBitPS(819200);
