edit-icon download-icon

Quick start

Last Updated: Mar 06, 2018

The basic file upload and download processes are demonstrated as follows. For more information, see the following directories of this project:

Sample directory (including demos of local file upload, file download, resumable upload, and callback setting) Click to view details.

You can also run git clone project and set necessary parameters:
config

Then, run the project as follows:
sample

Step 1. Initialize the OSSClient

The initialization process mainly includes the following steps: endpoint settings, authentication mode settings, and client parameter settings. Two authentication modes are available: self-signed mode and STS authentication mode. To use the STS authentication, see Resource Access Management to learn more about the RAM. Assuming that you have activated the RAM service and learned the RAM service and how to obtain sub-account AccessKeyId, SecretKeyId, and RoleArn.

Complete the parameter information of AccessKeyId, SecretKeyId, and RoleArn in the script files. You can enable a local HTTP service with Python. Access local services using the client codes to obtain the StsToken.AccessKeyId, StsToken.SecretKeyId, and StsToken.SecurityToken.

For more information, see STS instructions in the sample: Click to view details..

  1. String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
  2. // We recommend that you initialize OSSClient using STS on the mobile device.
  3. // For more information, see STS instructions in the sample.(https://github.com/aliyun/aliyun-oss-android-sdk/tree/master/app/src/main/java/com/alibaba/sdk/android/oss/app)
  4. OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider("<StsToken.AccessKeyId>", "<StsToken.SecretKeyId>", "<StsToken.SecurityToken>");
  5. //If the configuration class is not set, use the default configurations. For more information, see the configuration class.
  6. ClientConfiguration conf = new ClientConfiguration();
  7. conf.setConnectionTimeout(15 * 1000); // Connection time-out. The default value is 15 seconds.
  8. conf.setSocketTimeout(15 * 1000); // Socket time-out. The default value is 15 seconds.
  9. conf.setMaxConcurrentRequest(5); // The maximum number of concurrent requests. The default value is 5.
  10. conf.setMaxErrorRetry(2); // The maximum number of retry attempts after each failed attempt. The default value is 2.
  11. //When the feature is enabled, you can view logs in the console and write a log file into the mobile phone SD card under SDCard_path\OSSLog\logs.csv. This feature is disabled by default.
  12. //The logs record the request data, returned data, and exception information in OSS operations.
  13. //Such as requestId and response header
  14. //Android_version: 5.1 Android version
  15. //mobile_model: XT1085 Android mobile phone model
  16. //Network_state: connected Network status
  17. //network_type: WIFI Network connection type
  18. //Specific operations:
  19. //[2017-09-05 16:54:52] - Encounter local execpiton: //java.lang.IllegalArgumentException: The bucket name is invalid.
  20. //A bucket name must:
  21. //1) be comprised of lower-case characters, numbers, or dash(-);
  22. //2) start with lower case or numbers;
  23. //3) be between 3-63 characters long.
  24. //------>end of log
  25. OSSLog.enableLog();
  26. OSS oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);

Initialization of upload and download requests using the OSSClient is thread-safe. You can run multiple tasks concurrently.

Step 2. Upload a file

Assuming that you already have a bucket in the OSS console. You can use the following codes to upload a local file to OSS:

  1. // Construct an upload request
  2. PutObjectRequest put = new PutObjectRequest("<bucketName>", "<objectKey>", "<uploadFilePath>");
  3. // You can set progress callback during the asynchronous upload
  4. put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
  5. @Override
  6. public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
  7. Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
  8. }
  9. });
  10. OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
  11. @Override
  12. public void onSuccess(PutObjectRequest request, PutObjectResult result) {
  13. Log.d("PutObject", "UploadSuccess");
  14. }
  15. @Override
  16. public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
  17. // Request exception
  18. if (clientExcepion != null) {
  19. // Local exception, such as a network exception
  20. clientExcepion.printStackTrace();
  21. }
  22. if (serviceException != null) {
  23. // Service exception
  24. Log.e("ErrorCode", serviceException.getErrorCode());
  25. Log.e("RequestId", serviceException.getRequestId());
  26. Log.e("HostId", serviceException.getHostId());
  27. Log.e("RawMessage", serviceException.getRawMessage());
  28. }
  29. }
  30. });
  31. // task.cancel(); // You can cancel the task
  32. // task.waitUntilFinished(); // Wait until the task is complete

Step 3. Download a specified file

The following code downloads the specified object, (you must handle the input stream of the returned data):

  1. // Construct a file download request.
  2. GetObjectRequest get = new GetObjectRequest("<bucketName>", "<objectKey>");
  3. OSSAsyncTask task = oss.asyncGetObject(get, new OSSCompletedCallback<GetObjectRequest, GetObjectResult>() {
  4. @Override
  5. public void onSuccess(GetObjectRequest request, GetObjectResult result) {
  6. // Request succeeds
  7. Log.d("Content-Length", "" + getResult.getContentLength());
  8. InputStream inputStream = result.getObjectContent();
  9. byte[] buffer = new byte[2048];
  10. int len;
  11. try {
  12. while ((len = inputStream.read(buffer)) != -1) {
  13. // Process the downloaded data.
  14. }
  15. } catch (IOException e) {
  16. e.printStackTrace();
  17. }
  18. }
  19. @Override
  20. public void onFailure(GetObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
  21. // Request exception
  22. if (clientExcepion != null) {
  23. // Local exception, such as a network exception
  24. clientExcepion.printStackTrace();
  25. }
  26. if (serviceException != null) {
  27. // Service exception
  28. Log.e("ErrorCode", serviceException.getErrorCode());
  29. Log.e("RequestId", serviceException.getRequestId());
  30. Log.e("HostId", serviceException.getHostId());
  31. Log.e("RawMessage", serviceException.getRawMessage());
  32. }
  33. }
  34. });
  35. // task.cancel(); // You can cancel the task
  36. // task.waitUntilFinished(); // If necessary, wait until the task is complete
Thank you! We've received your feedback.