This topic describes how to upload objects to OSS in Android.

Simple upload

Simple upload uses the PutObject operation to upload selected objects to OSS at a time. For more information, see PutObject in OSS API Reference.
  • Processing logic
    1. After selecting Upload, you can select the local file to load.
    2. OssDemo sends a request after obtaining the address of sts_server.
    3. sts_server returns AccessKeyId, AccessKeySecret, SecurityToken, and Expiration.
    4. After obtaining the information, OssDemo calls the SDK to create OSSClient and perform simple upload.
  • Code analysis
    1. Generate a Button control.
      Location:
       res/layout/content_main.xml
       Content:
       <Button
           style="? android:attr/buttonStyleSmall"
           android:layout_height="wrap_content"
           android:layout_width="wrap_content"
           android:text="@string/upload"
           android:id="@+id/upload" />
    2. Click Upload. Select the object to upload.

      Code segment for function implementation:

      Button upload = (Button) findViewById(R.id.upload);
       upload.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               Intent i = new Intent(
                       Intent.ACTION_PICK,
                       android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
               startActivityForResult(i, RESULT_UPLOAD_IMAGE);
           }
       }
    3. Call the upload API operation of the SDK.

      Code segment for function implementation:

      @Override
       protected void onActivityResult(int requestCode, int resultCode, Intent data) {
           super.onActivityResult(requestCode, resultCode, data);
           if ((requestCode == RESULT_UPLOAD_IMAGE || requestCode == RESULT_PAUSEABLEUPLOAD_IMAGE) && resultCode == RESULT_OK && null ! = data) {
               Uri selectedImage = data.getData();
               String[] filePathColumn = { MediaStore.Images.Media.DATA };
               Cursor cursor = getContentResolver().query(selectedImage,
                       filePathColumn, null, null, null);
               cursor.moveToFirst();
               int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
               String picturePath = cursor.getString(columnIndex);
               Log.d("PickPicture", picturePath);
               cursor.close();
               try {
                   Bitmap bm = ImageDisplayer.autoResizeFromLocalFile(picturePath);
                   displayImage(bm);
                   File file = new File(picturePath);
                   displayInfo("object: " + picturePath + "\nsize: " + String.valueOf(file.length()));
               }
               catch (IOException e) {
                   e.printStackTrace();
                   displayInfo(e.toString());
               }
               //Upload the object based on different operations.
               if (requestCode == RESULT_UPLOAD_IMAGE) {
                   final EditText editText = (EditText) findViewById(R.id.edit_text);
                   String objectName = editText.getText().toString();
                   //Call the simple upload operation to upload an object.
                   ossService.asyncPutImage(objectName, picturePath, getPutCallback(), new ProgressCallbackFactory<PutObjectRequest>().get());
               }
           }
       }

      The processing of the upload result is omitted here. For more information, see onSuccess and onFailure in the source code.

Multipart upload-based resumable upload

You can call the MultipartUpload operation of OSS to implement resumable upload.
  • Processing logic
    1. After selecting Upload, you can select the local file to load.
    2. OssDemo sends a request after obtaining the address of sts_server.
    3. sts_server returns AccessKeyId, AccessKeySecret, SecurityToken, and Expiration.
    4. After obtaining the information, OssDemo calls the SDK to create OSSClient and perform multipart upload.
    5. Click Pause. If the multipart upload task is not complete, click Continue to resume the upload from the position where the last upload stops.
  • Code analysis
    1. Generate a Button control.
      Location:
       res/layout/content_main.xml
       Content:
       <Button
           style="? android:attr/buttonStyleSmall"
           android:layout_height="wrap_content"
           android:layout_width="wrap_content"
           android:text="@string/multipart_upload"
           android:id="@+id/multipart_upload" />
    2. Click Upload. Select the object to upload.

      Code segment for function implementation:

      Button multipart_upload = (Button) findViewById(R.id.multipart_upload);
       multipart_upload.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               //To simplify the upload concurrency, run only one resumable upload task.
               Intent i = new Intent(
                       Intent.ACTION_PICK,
                       android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
               startActivityForResult(i, RESULT_PAUSEABLEUPLOAD_IMAGE);
           }
       }
       );
    3. Click Continue to complete resumable upload.

      Code segment for function implementation:

      Click Upload: //Call the MultipartUpload operation of the SDK to upload an object. task = ossService.asyncMultiPartUpload(objectName, picturePath, getMultiPartCallback().addCallback(new Runnable() {     @Override     public void run() {         pauseTaskStatus = TASK_NONE;         multipart_resume.setEnabled(false);         multipart_pause.setEnabled(false);         task = null;     } }}, new ProgressCallbackFactory<PauseableUploadRequest>().get()); The bottom-layer logic to encrypt the SDK: Implement resumable upload by using asyncUpload in multiPartUploadManager. //During resumable upload, PauseableUploadTask can be called to suspend a task. public PauseableUploadTask asyncMultiPartUpload(String object,                                                 String localFile,                                                 @NonNull final OSSCompletedCallback<PauseableUploadRequest, PauseableUploadResult> userCallback,                                                 final OSSProgressCallback<PauseableUploadRequest> userProgressCallback) {     if (object.equals("")) {         Log.w("AsyncMultiPartUpload", "ObjectNull");         return null;     }     File file = new File(localFile);     if (! file.exists()) {         Log.w("AsyncMultiPartUpload", "FileNotExist");         Log.w("LocalFile", localFile);         return null;     }     Log.d("MultiPartUpload", localFile);     PauseableUploadTask task = multiPartUploadManager.asyncUpload(object, localFile, userCallback, userProgressCallback);     return task; }