Ahmad Arslan
Ahmad Arslan

Reputation: 4528

Android: Media is not Accessing after uploading to private bucket using AWS

Bucket which is created on AWS is private. I am not able to access the file when uploading with private access mode. Uploading successfully when uploading media using below method.

Bucket Name with URL getting from util class

    String bucketName = Util.getBucketNameFromUrl(uploadPath);
    String fileNameIncludingSubFolders = localPath.substring(localPath.lastIndexOf("/")+1);
    Uri mUri = Uri.parse(localPath);

File for uploading to AWS

File mFile = new File(mUri.toString().trim());

        AmazonS3Client s3Client = new AmazonS3Client(  Ut.getCredentialsCognito(context));
        PutObjectRequest por = new PutObjectRequest(bucketName, fileNameIncludingSubFolders, mFile);
        por.setProgressListener(new ProgressListener() {

            @Override
            public void progressChanged(ProgressEvent prgEvent) {
                if (progressUpdate != null) {
                    progressUpdate.progressStatus(String.valueOf(prgEvent.getBytesTransferred()));
                }
            }
        });

Access mode is Private when Uploading media file

        try {
            por.setCannedAcl(CannedAccessControlList.Private);
            s3Client.putObject(por);
        } catch (Exception e) {
            e.printStackTrace();
        }

Upvotes: 1

Views: 115

Answers (1)

Salmaan
Salmaan

Reputation: 3624

All you are doing is fine. Upload will be working good.
Only thing you require is to generate signed URL.
Use AWS SDK GeneratePresignedUrlRequest for this. This class have many methods, you can also set expiry date for the link and other stuff.

AWSCredentials awsCredentials = new BasicAWSCredentials("ACCESS_KEY_ID", "SECRET_KEY_ID");
AmazonS3 s3client = new AmazonS3Client(awsCredentials );
GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, fileKey);
URL objectURL = s3client.generatePresignedUrl(request);

You can find the file key and key name as following:
https://s3-[region]..amazonaws.com/[bucket name]/[file key]

Upvotes: 1

Related Questions