All Products
Search
Document Center

Object Storage Service:Simple upload

Last Updated:Mar 07, 2024

Simple upload is an upload method that you can use to upload an object by calling the PutObject operation. You can use simple upload to upload local files and byte arrays in binary.

Usage notes

  • Before you run the sample code in this topic, you must create an OSSClient instance by using methods such as using a custom domain name or Security Token Service (STS). For more information, see Initialization.

Upload a local file

You can upload a local file to Object Storage Service (OSS) in synchronous or asynchronous mode.

Upload a local file in synchronous mode

The following sample code provides an example on how to upload a local file named examplefile.txt to the exampleobject.txt object in the exampledir directory of the examplebucket bucket in synchronous mode:

// Construct an upload request. 
// Specify the name of the bucket, the full path of the object, and the full path of the local file. In this example, the name of the bucket is examplebucket, the full path of the object is exampledir/exampleobject.txt, and the full path of the local file is /storage/emulated/0/oss/examplefile.txt. 
// Do not include the bucket name in the full path of the object. 
PutObjectRequest put = new PutObjectRequest("examplebucket", "exampledir/exampleobject.txt", "/storage/emulated/0/oss/examplefile.txt");

// (Optional) Specify the object metadata. 
 ObjectMetadata metadata = new ObjectMetadata();
// metadata.setContentType("application/octet-stream"); // Set content-type. 
// metadata.setContentMD5(BinaryUtil.calculateBase64Md5(uploadFilePath)); // Specify the MD5 hash that is used for MD5 verification. 
// Set the ACL of the object to private. 
metadata.setHeader("x-oss-object-acl", "private");
// Set the storage class of the object to Standard. 
metadata.setHeader("x-oss-storage-class", "Standard");
// Specify that the uploaded object that has the same name as an existing object does not overwrite the existing object. 
// metadata.setHeader("x-oss-forbid-overwrite", "true");
// Specify one or more tags for the object. 
// metadata.setHeader("x-oss-tagging", "a:1");
// Specify the server-side encryption algorithm that is used to encrypt the object when OSS creates the object. 
// metadata.setHeader("x-oss-server-side-encryption", "AES256");
// Specify the CMK that is managed by KMS. This parameter takes effect only when x-oss-server-side-encryption is set to KMS. 
// metadata.setHeader("x-oss-server-side-encryption-key-id", "9468da86-3509-4f8d-a61e-6eab1eac****");

put.setMetadata(metadata);

try {
    PutObjectResult putResult = oss.putObject(put);

    Log.d("PutObject", "UploadSuccess");
    Log.d("ETag", putResult.getETag());
    Log.d("RequestId", putResult.getRequestId());
} catch (ClientException e) {
    // Handle client-side exceptions, such as network errors. 
    e.printStackTrace();
} catch (ServiceException e) {
    // Handle server-side exceptions. 
    Log.e("RequestId", e.getRequestId());
    Log.e("ErrorCode", e.getErrorCode());
    Log.e("HostId", e.getHostId());
    Log.e("RawMessage", e.getRawMessage());
}

For scoped storage of Android 10 and later, you can use the URI of a file to upload the file to OSS.

// Construct an upload request. 
// Specify the name of the bucket and the full path of the object. In this example, the bucket name is examplebucket and the full path of the object is exampledir/exampleobject.txt. 
// Do not include the bucket name in the full path of the object. 
PutObjectRequest put = new PutObjectRequest("examplebucket", "exampledir/exampleobject.txt",fileUri);

// Specify object metadata. 
// ObjectMetadata metadata = new ObjectMetadata();
// Specify Content-Type. 
// metadata.setContentType("text/plain"); 
// Specify the MD5 hash that is used for MD5 verification. 
// metadata.setContentMD5(BinaryUtil.calculateBase64Md5(uploadFilePath)); 
// put.setMetadata(metadata);

try {
    PutObjectResult putResult = oss.putObject(put);

    Log.d("PutObject", "UploadSuccess");
    Log.d("ETag", putResult.getETag());
    Log.d("RequestId", putResult.getRequestId());
} catch (ClientException e) {
    // Handle client-side exceptions, such as network errors. 
    e.printStackTrace();
} catch (ServiceException e) {
    // Handle server-side exceptions. 
    Log.e("RequestId", e.getRequestId());
    Log.e("ErrorCode", e.getErrorCode());
    Log.e("HostId", e.getHostId());
    Log.e("RawMessage", e.getRawMessage());
}

Upload a local file in asynchronous mode

Note

If you use OSS SDK for Android, the synchronous mode can be used to upload a local file to OSS only in the subthread. You cannot upload a local file in the UI thread in synchronous mode. Otherwise, an exception occurs. To upload a local file in the UI thread, use the asynchronous mode.

The following code provides an example on how to upload a local file named examplefile.txt to the exampleobject.txt object in the exampledir directory of the examplebucket bucket in asynchronous mode:

// Construct an upload request. 
// Specify the name of the bucket, the full path of the object, and the full path of the local file. In this example, the name of the bucket is examplebucket, the full path of the object is exampledir/exampleobject.txt, and the full path of the local file is /storage/emulated/0/oss/examplefile.txt. 
// Do not include the bucket name in the full path of the object. 
PutObjectRequest put = new PutObjectRequest("examplebucket", "exampledir/exampleobject.txt", "/storage/emulated/0/oss/examplefile.txt");

// When you upload the local file in asynchronous mode, you can configure a progress callback. 
put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
    @Override
    public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
        Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
    }
});

OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
    @Override
    public void onSuccess(PutObjectRequest request, PutObjectResult result) {
        Log.d("PutObject", "UploadSuccess");
        Log.d("ETag", result.getETag());
        Log.d("RequestId", result.getRequestId());
    }

    @Override
    public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
        // Handle request exceptions. 
        if (clientExcepion != null) {
            // Handle client-side exceptions, such as network errors. 
            clientExcepion.printStackTrace();
        }
        if (serviceException != null) {
            // Handle server-side exceptions. 
            Log.e("ErrorCode", serviceException.getErrorCode());
            Log.e("RequestId", serviceException.getRequestId());
            Log.e("HostId", serviceException.getHostId());
            Log.e("RawMessage", serviceException.getRawMessage());
        }
    }
});
// Cancel the upload task. 
// task.cancel(); 
// Wait until the upload task is complete. 
// task.waitUntilFinished(); 

For scoped storage of Android 10 and later, you can use the URI of a file to upload the file to OSS.

// Construct an upload request. 
// Specify the name of the bucket and the full path of the object. In this example, the bucket name is examplebucket and the full path of the object is exampledir/exampleobject.txt. 
// Do not include the bucket name in the full path of the object. 
PutObjectRequest put = new PutObjectRequest("examplebucket", "exampledir/exampleobject.txt", fileUri);

// When you upload the local file in asynchronous mode, you can configure a progress callback. 
put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
    @Override
    public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
        Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
    }
});

OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
    @Override
    public void onSuccess(PutObjectRequest request, PutObjectResult result) {
        Log.d("PutObject", "UploadSuccess");
        Log.d("ETag", result.getETag());
        Log.d("RequestId", result.getRequestId());
    }

    @Override
    public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
        // Handle request exceptions. 
        if (clientExcepion != null) {
            // Handle client-side exceptions, such as network errors. 
            clientExcepion.printStackTrace();
        }
        if (serviceException != null) {
            // Handle server-side exceptions. 
            Log.e("ErrorCode", serviceException.getErrorCode());
            Log.e("RequestId", serviceException.getRequestId());
            Log.e("HostId", serviceException.getHostId());
            Log.e("RawMessage", serviceException.getRawMessage());
        }
    }
});
// Cancel the upload task. 
// task.cancel(); 
// Wait until the upload task is complete. 
// task.waitUntilFinished(); 

Upload a byte array in binary

The following code provides an example on how to upload a byte array in binary to the exampleobject.txt object in the exampledir directory of the examplebucket bucket in synchronous mode:

byte[] uploadData = new byte[100 * 1024];
new Random().nextBytes(uploadData);

// Construct an upload request. 
// Specify the name of the bucket and the full path of the object. In this example, the bucket name is examplebucket and the full path of the object is exampledir/exampleobject.txt. 
// Do not include the bucket name in the full path of the object. 
PutObjectRequest put = new PutObjectRequest("examplebucket", "exampledir/exampleobject.txt", uploadData);

try {
    PutObjectResult putResult = oss.putObject(put);

    Log.d("PutObject", "UploadSuccess");
    Log.d("ETag", putResult.getETag());
    Log.d("RequestId", putResult.getRequestId());
} catch (ClientException e) {
    // Handle client-side exceptions, such as network errors. 
    e.printStackTrace();
} catch (ServiceException e) {
    // Handle server-side exceptions. 
    Log.e("RequestId", e.getRequestId());
    Log.e("ErrorCode", e.getErrorCode());
    Log.e("HostId", e.getHostId());
    Log.e("RawMessage", e.getRawMessage());
}

References

  • For the complete sample code that is used to perform simple upload, visit GitHub.

  • For more information about the API operation that you can call to perform simple upload, see PutObject.

  • For more information about how to initialize an OSSClient instance, see Initialization.