prime
prime

Reputation: 799

How to wait the main thread until the AWS S3 file upload finished

Based on some user inputs, I want to upload some images(around 10-15) to AWS S3 buckets. Once It completed, front end should display the uploaded images to the client.

But According to my current implementation, Before uploading the images to S3 bucket, the front end page is getting the response from the backend.

I'm using the below code part to upload files to S3.

      AmazonS3 s3Client = AmazonS3ClientBuilder.defaultClient();

      ObjectMetadata putObjectMetaData = new ObjectMetadata();
      putObjectMetaData.setContentType(contentType);

      PutObjectRequest putObject =
          new PutObjectRequest(s3BucketPath, fileName, fileStream, new ObjectMetadata())
              .withCannedAcl(CannedAccessControlList.PublicRead);
      putObject.setMetadata(putObjectMetaData);

      PutObjectResult result = s3Client.putObject(putObject);

As I understood, S3 upload is going on a separate thread. Is there a way to do the S3 upload from the same main thread. Or is there any other way to wait until the S3 upload is finished?

I really appreciate your replies.

Upvotes: 0

Views: 3702

Answers (1)

Bee
Bee

Reputation: 12512

You can try the Transfer Manager[1]. Full example here[2].


import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.s3.transfer.MultipleFileUpload;
import com.amazonaws.services.s3.transfer.TransferManager;
import com.amazonaws.services.s3.transfer.TransferManagerBuilder;
import com.amazonaws.services.s3.transfer.Upload;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;

-----------------------------------

File f = new File(file_path);
TransferManager xfer_mgr = TransferManagerBuilder.standard().build();
try {
    Upload xfer = xfer_mgr.upload(bucket_name, key_name, f);
    // loop with Transfer.isDone()
    XferMgrProgress.showTransferProgress(xfer);
    //  or block with Transfer.waitForCompletion()
    XferMgrProgress.waitForCompletion(xfer);
} catch (AmazonServiceException e) {
    System.err.println(e.getErrorMessage());
    System.exit(1);
}
xfer_mgr.shutdownNow();

[1] https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/examples-s3-transfermanager.html [2] https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/java/example_code/s3/src/main/java/aws/example/s3/XferMgrUpload.java

Upvotes: 1

Related Questions