API | Operation | Description |
Uploading object in whole | Uploads object to bucket. | |
Uploading object by using HTML form | Uploads object by using HTML form. | |
Appending parts | Uploads object by appending parts. |
API | Operation | Description |
Querying multipart uploads | Queries in-progress multipart uploads. | |
Initializing multipart upload operation | Initializes multipart upload operation. | |
Uploading parts | Uploads object in parts. | |
Copying part | Copies object as part. | |
Querying uploaded parts | Queries the uploaded parts of a multipart upload. | |
Completing a multipart upload | Completes the multipart upload of a file. | |
Aborting a multipart upload | Aborts a multipart upload and deletes the uploaded parts. |
Content-Length
header is not specified.Content-Length
header is specified.// Create a TransferManager instance, which is used to call the advanced API later.TransferManager createTransferManager() {// Create a COSClient client, which is the basic instance for accessing the COS service.// For the detailed code, see **Simple Operations** > **Creating COSClient instance** in this document.COSClient cosClient = createCOSClient();// Set the thread pool size. We recommend you set the size of your thread pool to 16 or 32 to maximize network resource utilization, provided your client and COS networks are sufficient (for example, uploading a file to a COS bucket from a CVM instance in the same region).// We recommend you use a smaller value to avoid timeout caused by slow network speed if you are transferring data over a public network with poor bandwidth quality.ExecutorService threadPool = Executors.newFixedThreadPool(32);// Pass a `threadpool`; otherwise, a single-thread pool will be generated in `TransferManager` by default.TransferManager transferManager = new TransferManager(cosClient, threadPool);// Set the configuration items of the advanced API.// Set the threshold and part size for multipart upload to 5 MB and 1 MB respectively.TransferManagerConfiguration transferManagerConfiguration = new TransferManagerConfiguration();transferManagerConfiguration.setMultipartUploadThreshold(5*1024*1024);transferManagerConfiguration.setMinimumUploadPartSize(1*1024*1024);transferManager.setConfiguration(transferManagerConfiguration);return transferManager;}
TransferManagerConfiguration
class is used to record the configuration information of the advanced API. Its main members are as described below:Member | Configuration Method | Description | Type |
minimumUploadPartSize | Set method | Part size of the multipart upload in bytes. Default value: 5 MB. | long |
multipartUploadThreshold | Set method | If a file is greater than or equal to this value in bytes, it will be uploaded in concurrent parts. Default value: 5 MB. | long |
multipartCopyThreshold | Set method | If a file is greater than or equal to this value in bytes, it will be copied in concurrent parts. Default value: 5 GB. | long |
multipartCopyPartSize | Set method | Part size in bytes for multipart copy. Default value: 100 MB. | long |
void shutdownTransferManager(TransferManager transferManager) {// If the parameter is set to `true`, the COSClient instance in the TransferManager instance will also be shut down at the same time.// If the parameter is set to `false`, the COSClient instance in the TransferManager instance will not be shut down.transferManager.shutdownNow(true);}
// Upload an object.public Upload upload(final PutObjectRequest putObjectRequest)throws CosServiceException, CosClientException;
// Before using the advanced API, you must make sure that the process contains a TransferManager instance; if not, then create one.// For the detailed code, see **Advanced API** > **Creating TransferManager instance** in this document.TransferManager transferManager = createTransferManager();// Enter the bucket name in the format of `BucketName-APPID`.String bucketName = "examplebucket-1250000000";// Object key, which is the unique identifier of the object in the bucket.String key = "exampleobject";// Local file path.String localFilePath = "/path/to/localFile";File localFile = new File(localFilePath);PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);// If you need to set the custom headers of the object, refer to the following code; otherwise, omit the following lines. For more information on custom headers, visit https://www.tencentcloud.com/document/product/436/13361?from_cn_redirect=1.ObjectMetadata objectMetadata = new ObjectMetadata();// To set `Content-Type`, `Cache-Control`, `Content-Disposition`, `Content-Encoding`, or `Expires` as a custom header, use `objectMetadata.setHeader()`.objectMetadata.setHeader(key, value);// To set a custom header like `x-cos-meta-[custom suffix]`, use:Map<String, String> userMeta = new HashMap<String, String>();userMeta.put("x-cos-meta-[custom suffix]", "value");objectMetadata.setUserMetadata(userMeta);putObjectRequest.withMetadata(objectMetadata);try {// The advanced API will return an async result `Upload`.// You can synchronously call the `waitForUploadResult` method to wait for the upload to complete. If the upload is successful, `UploadResult` will be returned; otherwise, an exception will be reported.Upload upload = transferManager.upload(putObjectRequest);UploadResult uploadResult = upload.waitForUploadResult();} catch (CosServiceException e) {e.printStackTrace();} catch (CosClientException e) {e.printStackTrace();} catch (InterruptedException e) {e.printStackTrace();}// After confirming that the process no longer uses the TransferManager instance, shut it down.// For the detailed code, see **Advanced API** > **Shutting down TransferManager instance** in this document.shutdownTransferManager(transferManager);
Parameter | Description | Type |
putObjectRequest | File upload request | PutObjectRequest |
Request Member | Configuration Method | Description | Type |
bucketName | Constructor or set method | String | |
key | Constructor or set method | Unique identifier of the object in the bucket. For example, if an object's access endpoint is examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/doc/picture.jpg , its key is doc/picture.jpg . For more information, see Object Overview. | String |
file | Constructor or set method | Local file | File |
input | Constructor or set method | Input stream | InputStream |
metadata | Constructor or set method | File metadata | ObjectMetadata |
trafficLimit | Set method | Traffic limit on the uploaded object in bit/s. There is no limit by default. | Int |
Upload
is returned. You can query whether the upload is complete, or wait for the upload to complete.CosClientException
or CosServiceException
exception will be reported. For more information, see Troubleshooting.UploadResult
class records the information of the uploaded object requested by calling the waitForUploadResult()
method from the Upload
class. Its main members are as described below:Member | Description | Type |
bucketName | String | |
key | Unique identifier of the object in the bucket. For example, if an object's access endpoint is examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/do/picture.jpg , its key is doc/picture.jpg . For more information, see Object Overview. | String |
requestId | Request ID | String |
dateStr | Current server time | String |
versionId | Version ID of the object returned when the bucket has versioning enabled | String |
crc64Ecma | CRC64 value computed by the server based on the object content | String |
InputStream
type (and its subtypes).// Upload an object.public Upload upload(final PutObjectRequest putObjectRequest)throws CosServiceException, CosClientException;
// Before using the advanced API, you must make sure that the process contains a TransferManager instance; if not, then create one.// For the detailed code, see **Advanced API** > **Creating TransferManager instance** in this document.TransferManager transferManager = createTransferManager();// Enter the bucket name in the format of `BucketName-APPID`.String bucketName = "examplebucket-1250000000";// Object key, which is the unique identifier of the object in the bucket.String key = "exampleobject";// Here, a `ByteArrayInputStream` stream is created as an example. In practice, you should create a stream of the `InputStream` type for upload.long inputStreamLength = 1024 * 1024;byte data[] = new byte[inputStreamLength];InputStream inputStream = new ByteArrayInputStream(data);ObjectMetadata objectMetadata = new ObjectMetadata();// If you can get the exact length of the uploaded stream, we recommend you enter `Content-Length`.// Otherwise, the following line can be omitted, but the advanced API cannot use multipart upload.objectMetadata.setContentLength(inputStreamLength);PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, inputStream, objectMetadata);try {// The advanced API will return an async result `Upload`.// You can synchronously call the `waitForUploadResult` method to wait for the upload to complete. If the upload is successful, `UploadResult` will be returned; otherwise, an exception will be reported.Upload upload = transferManager.upload(putObjectRequest);UploadResult uploadResult = upload.waitForUploadResult();} catch (CosServiceException e) {e.printStackTrace();} catch (CosClientException e) {e.printStackTrace();} catch (InterruptedException e) {e.printStackTrace();}// After confirming that the process no longer uses the TransferManager instance, shut it down.// For the detailed code, see **Advanced API** > **Shutting down TransferManager instance** in this document.shutdownTransferManager(transferManager);
Parameter | Description | Type |
putObjectRequest | File upload request | PutObjectRequest |
Request Member | Configuration Method | Description | Type |
bucketName | Constructor or set method | String | |
key | Constructor or set method | Unique identifier of the object in the bucket. For example, if an object's access endpoint is examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/doc/picture.jpg , its key is doc/picture.jpg . For more information, see Object Overview. | String |
file | Constructor or set method | Local file | File |
input | Constructor or set method | Input stream | InputStream |
metadata | Constructor or set method | File metadata | ObjectMetadata |
trafficLimit | Set method | Traffic limit on the uploaded object in bit/s. There is no limit by default. | Int |
Upload
is returned. You can query whether the upload is complete, or wait for the upload to complete.CosClientException
or CosServiceException
exception will be reported. For more information, see Troubleshooting.UploadResult
class records the information of the uploaded object requested by calling the waitForUploadResult()
method from the Upload
class. Its main members are as described below:Member | Description | Type |
bucketName | String | |
key | Unique identifier of the object in the bucket. For example, if an object's access endpoint is examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/do/picture.jpg , its key is doc/picture.jpg . For more information, see Object Overview. | String |
requestId | Request ID | String |
dateStr | Current server time | String |
versionId | Version ID of the object returned when the bucket has versioning enabled | String |
crc64Ecma | CRC64 value computed by the server based on the object content | String |
// Upload an object.public Upload upload(final PutObjectRequest putObjectRequest)throws CosServiceException, CosClientException;
// You can adjust the following sample code as needed to form your own code.void showTransferProgress(Transfer transfer) {// Here, `Transfer` is the parent class of the async upload result `Upload`.System.out.println(transfer.getDescription());// Use `transfer.isDone()` to check whether the upload is complete.while (transfer.isDone() == false) {try {// Get the progress every two seconds.Thread.sleep(2000);} catch (InterruptedException e) {return;}TransferProgress progress = transfer.getProgress();long sofar = progress.getBytesTransferred();long total = progress.getTotalBytesToTransfer();double pct = progress.getPercentTransferred();System.out.printf("upload progress: [%d / %d] = %.02f%%\\n", sofar, total, pct);}// If the upload is complete, `Completed` will be returned; otherwise, `Failed` will be returned.System.out.println(transfer.getState());}
// Before using the advanced API, you must make sure that the process contains a TransferManager instance; if not, then create one.// For the detailed code, see **Advanced API** > **Creating TransferManager instance** in this document.TransferManager transferManager = createTransferManager();// Enter the bucket name in the format of `BucketName-APPID`.String bucketName = "examplebucket-1250000000";// Object key, which is the unique identifier of the object in the bucket.String key = "exampleobject";// Local file path.String localFilePath = "/path/to/localFile";File localFile = new File(localFilePath);PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);try {// The advanced API will return an async result `Upload`.Upload upload = transferManager.upload(putObjectRequest);// Print the upload progress until the upload is complete.showTransferProgress(upload);// Capture possible exceptions.UploadResult uploadResult = upload.waitForUploadResult();} catch (CosServiceException e) {e.printStackTrace();} catch (CosClientException e) {e.printStackTrace();} catch (InterruptedException e) {e.printStackTrace();}// After confirming that the process no longer uses the TransferManager instance, shut it down.// For the detailed code, see **Advanced API** > **Shutting down TransferManager instance** in this document.shutdownTransferManager(transferManager);
getProgress
method of the Upload
class to get the TransferProgress
class, which has the following three methods to get the upload progress:Method | Description | Type |
getBytesTransferred | Gets the number of uploaded bytes. | long |
getTotalBytesToTransfer | Gets the total number of bytes of the file. | long |
getPercentTransferred | Gets the percentage of the number of uploaded bytes. | double |
Parameter | Description | Type |
putObjectRequest | File upload request | PutObjectRequest |
Request Member | Configuration Method | Description | Type |
bucketName | Constructor or set method | String | |
key | Constructor or set method | Unique identifier of the object in the bucket. For example, if an object's access endpoint is examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/doc/picture.jpg , its key is doc/picture.jpg . For more information, see Object Overview. | String |
file | Constructor or set method | Local file | File |
input | Constructor or set method | Input stream | InputStream |
metadata | Constructor or set method | File metadata | ObjectMetadata |
trafficLimit | Set method | Traffic limit on the uploaded object in bit/s. There is no limit by default. | Int |
Upload
is returned. You can query whether the upload is complete, or wait for the upload to complete.CosClientException
or CosServiceException
exception will be reported. For more information, see Troubleshooting.UploadResult
class records the information of the uploaded object requested by calling the waitForUploadResult()
method from the Upload
class. Its main members are as described below:Member | Description | Type |
bucketName | String | |
key | Unique identifier of the object in the bucket. For example, if an object's access endpoint is examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/do/picture.jpg , its key is doc/picture.jpg . For more information, see Object Overview. | String |
requestId | Request ID | String |
dateStr | Current server time | String |
versionId | Version ID of the object returned when the bucket has versioning enabled | String |
crc64Ecma | CRC64 value computed by the server based on the object content | String |
// Upload an object.public Upload upload(final PutObjectRequest putObjectRequest)throws CosServiceException, CosClientException;
// Before using the advanced API, you must make sure that the process contains a TransferManager instance; if not, then create one.// For the detailed code, see **Advanced API** > **Creating TransferManager instance** in this document.TransferManager transferManager = createTransferManager();// Enter the bucket name in the format of `BucketName-APPID`.String bucketName = "examplebucket-1250000000";// Object key, which is the unique identifier of the object in the bucket.String key = "exampleobject";// Local file path.String localFilePath = "/path/to/localFile";File localFile = new File(localFilePath);PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);try {// The advanced API will return an async result `Upload`.Upload upload = transferManager.upload(putObjectRequest);// Wait three seconds for part of the file to be uploaded.Thread.sleep(3000);// Pause the upload and get a `PersistableUpload` instance for resuming the upload later.PersistableUpload persistableUpload = upload.pause();// Complex pausing and resuming:// `PersistableUpload` instance can be used to serialize the file content and store it and then deserialize it to resume the upload.// persistableUpload.serialize(out);// Resume the upload.upload = transferManager.resumeUpload(persistableUpload);// Capture possible exceptions.UploadResult uploadResult = upload.waitForUploadResult();// Or directly cancel the upload.// upload.abort();} catch (CosServiceException e) {e.printStackTrace();} catch (CosClientException e) {e.printStackTrace();} catch (InterruptedException e) {e.printStackTrace();}// After confirming that the process no longer uses the TransferManager instance, shut it down.// For the detailed code, see **Advanced API** > **Shutting down TransferManager instance** in this document.shutdownTransferManager(transferManager);
Parameter | Description | Type |
putObjectRequest | File upload request | PutObjectRequest |
Request Member | Configuration Method | Description | Type |
bucketName | Constructor or set method | String | |
key | Constructor or set method | Unique identifier of the object in the bucket. For example, if an object's access endpoint is examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/doc/picture.jpg , its key is doc/picture.jpg . For more information, see Object Overview. | String |
file | Constructor or set method | Local file | File |
input | Constructor or set method | Input stream | InputStream |
metadata | Constructor or set method | File metadata | ObjectMetadata |
trafficLimit | Set method | Traffic limit on the uploaded object in bit/s. There is no limit by default. | Int |
Upload
is returned. You can query whether the upload is complete, or wait for the upload to complete.CosClientException
or CosServiceException
exception will be reported. For more information, see Troubleshooting.UploadResult
class records the information of the uploaded object requested by calling the waitForUploadResult()
method from the Upload
class. Its main members are as described below:Member | Description | Type |
bucketName | String | |
key | Unique identifier of the object in the bucket. For example, if an object's access endpoint is examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/do/picture.jpg , its key is doc/picture.jpg . For more information, see Object Overview. | String |
requestId | Request ID | String |
dateStr | Current server time | String |
versionId | Version ID of the object returned when the bucket has versioning enabled | String |
crc64Ecma | CRC64 value computed by the server based on the object content | String |
public MultipleFileUpload uploadDirectory(String bucketName, String virtualDirectoryKeyPrefix,File directory, boolean includeSubdirectories);
// Before using the advanced API, you must make sure that the process contains a TransferManager instance; if not, then create one.// For the detailed code, see **Advanced API** > **Creating TransferManager instance** in this document.TransferManager transferManager = createTransferManager();// Enter the bucket name in the format of `BucketName-APPID`.String bucketName = "examplebucket-1250000000";// Set the prefix of the directory to upload the files to. If this parameter is set to `""`, the files will be uploaded to the root directory of the bucket.String cos_path = "/prefix";// Absolute path of the folder to be uploaded.String dir_path = "/path/to/localdir";// Whether to upload the subdirectories in the directory recursively. If this parameter is set to `true`, the files in the subdirectories will also be uploaded with the original directory structure unchanged.Boolean recursive = false;try {// Return an async result `Upload`. You can synchronously call `waitForUploadResult` to wait for the upload to complete. If the upload is successful, `UploadResult` will be returned; otherwise, an exception will be reported.MultipleFileUpload upload = transferManager.uploadDirectory(bucketName, cos_path, new File(dir_path), recursive);// You can choose to view the upload progress. For more information on the function, see **Advanced API** > **Uploading file** > **Displaying the upload progress**.showTransferProgress(upload);// You can also wait for the upload to complete.upload.waitForCompletion();} catch (CosServiceException e) {e.printStackTrace();} catch (CosClientException e) {e.printStackTrace();} catch (InterruptedException e) {e.printStackTrace();}// After confirming that the process no longer uses the TransferManager instance, shut it down.// For the detailed code, see **Advanced API** > **Shutting down TransferManager instance** in this document.shutdownTransferManager(transferManager);
Parameter | Description | Type |
bucketName | Name of the bucket in COS | GetObjectRequest |
virtualDirectoryKeyPrefix | Prefix of the objects in COS | String |
directory | Absolute path of the folder to be uploaded | File |
includeSubDirectory | Whether to upload subdirectories recursively | Boolean |
MultipleFileUpload
is returned. You can query whether the upload is complete, or wait for the upload to complete.CosClientException
or CosServiceException
exception will be reported. For more information, see Troubleshooting.COSClient
instances. You need to create a COSClient
instance before performing simple operations.COSClient
instances are concurrency safe. We recommend you create only one COSClient
instance for a process and then shut it down when it is no longer used to initiate requests.COSClient
instance.// Create a `COSClient` instance, which is used to initiate requests later.COSClient createCOSClient() {// Set the user identity information.// Log in to the [CAM console](https://console.tencentcloud.com/cam/capi) to view and manage the `SECRETID` and `SECRETKEY` of your project.String secretId = "SECRETID";String secretKey = "SECRETKEY";COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);// `ClientConfig` contains the COS client configuration for subsequent COS requests.ClientConfig clientConfig = new ClientConfig();// Set the bucket region.// For more information on COS regions, visit https://www.tencentcloud.com/document/product/436/6224?from_cn_redirect=1.clientConfig.setRegion(new Region("COS_REGION"));// Set the request protocol to `http` or `https`.// For v5.6.53 or earlier, HTTPS is recommended.// For v5.6.54 or later, HTTPS is used by default.clientConfig.setHttpProtocol(HttpProtocol.https);// The following settings are optional:// Set the read timeout period, which is 30s by default.clientConfig.setSocketTimeout(30*1000);// Set the connection timeout period, which is 30s by default.clientConfig.setConnectionTimeout(30*1000);// If necessary, set the HTTP proxy, IP, and port.clientConfig.setHttpProxyIp("httpProxyIp");clientConfig.setHttpProxyPort(80);// Generate a COS client.return new COSClient(cred, clientConfig);}
COSClient
instance with the temporary key.
This SDK does not generate temporary keys. For directions on how to generate a temporary key, see Generating and Using Temporary Keys.// Create a `COSClient` instance, which is used to initiate requests later.COSClient createCOSClient() {// Here, the temporary key information is needed.// For directions on how to generate a temporary key, visit https://www.tencentcloud.com/document/product/436/14048.String tmpSecretId = "TMPSECRETID";String tmpSecretKey = "TMPSECRETKEY";String sessionToken = "SESSIONTOKEN";COSCredentials cred = new BasicSessionCredentials(tmpSecretId, tmpSecretKey, sessionToken);// `ClientConfig` contains the COS client configuration for subsequent COS requests.ClientConfig clientConfig = new ClientConfig();// Set the bucket region.// For more information on COS regions, visit https://www.tencentcloud.com/document/product/436/6224?from_cn_redirect=1.clientConfig.setRegion(new Region("COS_REGION"));// Set the request protocol to `http` or `https`.// For v5.6.53 or earlier, HTTPS is recommended.// For v5.6.54 or later, HTTPS is used by default.clientConfig.setHttpProtocol(HttpProtocol.https);// The following settings are optional:// Set the read timeout period, which is 30s by default.clientConfig.setSocketTimeout(30*1000);// Set the connection timeout period, which is 30s by default.clientConfig.setConnectionTimeout(30*1000);// If necessary, set the HTTP proxy, IP, and port.clientConfig.setHttpProxyIp("httpProxyIp");clientConfig.setHttpProxyPort(80);// Generate a COS client.return new COSClient(cred, clientConfig);}
// Method 1. Upload a local file to COS.public PutObjectResult putObject(String bucketName, String key, File file)throws CosClientException, CosServiceException;// Method 2. Upload an input stream to COS.public PutObjectResult putObject(String bucketName, String key, InputStream input, ObjectMetadata metadata)throws CosClientException, CosServiceException;// Method 3. Encapsulate the two methods above to support more fine-grained parameter control, such as `content-type` and `content-disposition`.public PutObjectResult putObject(PutObjectRequest putObjectRequest)throws CosClientException, CosServiceException;
// Before using the COS API, make sure that the process contains a `COSClient` instance; if not, create one.// For the detailed code, see **Simple Operations** > **Creating COSClient instance** in this document.COSClient cosClient = createCOSClient();// Enter the bucket name in the format of `BucketName-APPID`.String bucketName = "examplebucket-1250000000";// Object key, which is the unique identifier of the object in the bucket.String key = "exampleobject";// Local file path.String localFilePath = "/path/to/localFile";File localFile = new File(localFilePath);PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);try {PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);System.out.println(putObjectResult.getRequestId());} catch (CosServiceException e) {e.printStackTrace();} catch (CosClientException e) {e.printStackTrace();} catch (InterruptedException e) {e.printStackTrace();}// After confirming that the process no longer uses the `COSClient` instance, shut it down.cosClient.shutdown();
Parameter | Description | Type |
putObjectRequest | File upload request | PutObjectRequest |
Request Member | Configuration Method | Description | Type | Required |
bucketName | Constructor or set method | String | Yes | |
key | Constructor or set method | Unique identifier of the object in the bucket. For example, if an object's access endpoint is examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/doc/picture.jpg , its key is doc/picture.jpg . For more information, see Object Overview. | String | Yes |
file | Constructor or set method | Local file | File | No |
input | Constructor or set method | Input stream | InputStream | No |
metadata | Constructor or set method | Object metadata | ObjectMetadata | No |
trafficLimit | Set method | Traffic limit on the uploaded object in bit/s. There is no limit by default. | Int | No |
ObjectMetadata
class is used to record the metadata of an object. Its main members are as described below:Member | Description | Type |
httpExpiresDate | Cache expiration time, which has the same value as the Expires field in the HTTP response header | Date |
ongoingRestore | Indicates that the object is being restored from the ARCHIVE storage class | Boolean |
userMetadata | Custom metadata prefixed with x-cos-meta- | Map<String, String> |
metadata | Headers other than custom metadata | Map<String, String> |
restoreExpirationTime | Expiration time for an object copy restored from ARCHIVE | Date |
PutObjectResult
is returned, including the file eTag
.CosClientException
or CosServiceException
exception will be reported. For more information, see Troubleshooting.PutObjectResult
class is used to return the result information. Its main members are as described below:Member | Description | Type |
requestId | Request ID | String |
dateStr | Current server time | String |
versionId | Version ID of the object returned when the bucket has versioning enabled | String |
eTag | The object's MD5 value returned by the simple upload API, such as 09cba091df696af91549de27b8e7d0f6 . *Note: Although the value of the ETag response header has double quotation marks, the value of the parsed eTag string here doesn't. * | String |
crc64Ecma | CRC64 value computed by the server based on the object content | String |
InputStream
type (and its subtypes).// Method 1. Upload a local file to COS.public PutObjectResult putObject(String bucketName, String key, File file)throws CosClientException, CosServiceException;// Method 2. Upload an input stream to COS.public PutObjectResult putObject(String bucketName, String key, InputStream input, ObjectMetadata metadata)throws CosClientException, CosServiceException;// Method 3. Encapsulate the two methods above to support more fine-grained parameter control, such as `content-type` and `content-disposition`.public PutObjectResult putObject(PutObjectRequest putObjectRequest)throws CosClientException, CosServiceException;
// Before using the COS API, make sure that the process contains a `COSClient` instance; if not, create one.// For the detailed code, see **Simple Operations** > **Creating COSClient instance** in this document.COSClient cosClient = createCOSClient();// Enter the bucket name in the format of `BucketName-APPID`.String bucketName = "examplebucket-1250000000";// Object key, which is the unique identifier of the object in the bucket.String key = "exampleobject";// Here, a `ByteArrayInputStream` stream is created as an example. In practice, you should create a stream of the `InputStream` type for upload.long inputStreamLength = 1024 * 1024;byte data[] = new byte[inputStreamLength];InputStream inputStream = new ByteArrayInputStream(data);ObjectMetadata objectMetadata = new ObjectMetadata();// If you can get the exact length of the uploaded stream, we recommend you enter `Content-Length`.// Otherwise, the following line can be omitted, but the advanced API cannot use multipart upload.objectMetadata.setContentLength(inputStreamLength);PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, inputStream, objectMetadata);try {PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);System.out.println(putObjectResult.getRequestId());} catch (CosServiceException e) {e.printStackTrace();} catch (CosClientException e) {e.printStackTrace();} catch (InterruptedException e) {e.printStackTrace();}// After confirming that the process no longer uses the `COSClient` instance, shut it down.cosClient.shutdown();
Parameter | Description | Type |
putObjectRequest | File upload request | PutObjectRequest |
Request Member | Configuration Method | Description | Type | Required |
bucketName | Constructor or set method | String | Yes | |
key | Constructor or set method | Unique identifier of the object in the bucket. For example, if an object's access endpoint is examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/doc/picture.jpg , its key is doc/picture.jpg . For more information, see Object Overview. | String | Yes |
file | Constructor or set method | Local file | File | No |
input | Constructor or set method | Input stream | InputStream | No |
metadata | Constructor or set method | Object metadata | ObjectMetadata | No |
trafficLimit | Set method | Traffic limit on the uploaded object in bit/s. There is no limit by default. | Int | No |
ObjectMetadata
class is used to record the metadata of an object. Its main members are as described below:Member | Description | Type |
httpExpiresDate | Cache expiration time, which has the same value as the Expires field in the HTTP response header | Date |
ongoingRestore | Indicates that the object is being restored from the ARCHIVE storage class | Boolean |
userMetadata | Custom metadata prefixed with x-cos-meta- | Map<String, String> |
metadata | Headers other than custom metadata | Map<String, String> |
restoreExpirationTime | Expiration time for an object copy restored from ARCHIVE | Date |
PutObjectResult
is returned, including the file eTag
.CosClientException
or CosServiceException
exception will be reported. For more information, see Troubleshooting.PutObjectResult
class is used to return the result information. Its main members are as described below:Member | Description | Type |
requestId | Request ID | String |
dateStr | Current server time | String |
versionId | Version ID of the object returned when the bucket has versioning enabled | String |
eTag | The object's MD5 value returned by the simple upload API, such as 09cba091df696af91549de27b8e7d0f6 . *Note: Although the value of the ETag response header has double quotation marks, the value of the parsed eTag string here doesn't. * | String |
crc64Ecma | CRC64 value computed by the server based on the object content | String |
/dir/example.txt
, the /dir
directory will be generated automatically. For more information, see "Uploading local file" in this document.// Before using the COS API, make sure that the process contains a `COSClient` instance; if not, create one.// For the detailed code, see **Simple Operations** > **Creating COSClient instance** in this document.COSClient cosClient = createCOSClient();// Enter the bucket name in the format of `BucketName-APPID`.String bucketName = "examplebucket-1250000000";// Specify the path of the directory to be created.String key = "/example/dir/";// Create an empty `ByteArrayInputStream` as an example.byte data[] = new byte[0];InputStream inputStream = new ByteArrayInputStream(data);ObjectMetadata objectMetadata = new ObjectMetadata();objectMetadata.setContentLength(0);PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, inputStream, objectMetadata);try {PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);System.out.println(putObjectResult.getRequestId());} catch (CosServiceException e) {e.printStackTrace();} catch (CosClientException e) {e.printStackTrace();} catch (InterruptedException e) {e.printStackTrace();}// After confirming that the process no longer uses the `COSClient` instance, shut it down.cosClient.shutdown();
public AppendObjectResult appendObject(AppendObjectRequest appendObjectRequest)throws CosServiceException, CosClientException
// Before using the COS API, make sure that the process contains a `COSClient` instance; if not, create one.// For the detailed code, see **Simple Operations** > **Creating COSClient instance** in this document.COSClient cosClient = createCOSClient