how to upload larger file( greater than 12 MB) to aws s3 bucket in using salesforce apex

Parbati Bose

I need some help for uploading large files into s3 bucket from salesforce apex server side.

I need to be able to split a blob and upload it to aws s3 bucket using Http PUT operation. I am able to do that upto 12 MB file in a single upload because that is the PUT request body size limit in Apex . So i need to be able to upload using multipart operation. I noticed s3 allows to upload in parts and gives back a uploadId. wondering if anyone has already done this before in salesforce apex code. it would be greatly appreciated.

Thanks in advance Parbati Bose.

Here is the code

public with sharing class AWSS3Service {

    private static Http http;

    @auraEnabled
    public static  void uploadToAWSS3( String fileToUpload , String filenm , String doctype){


        fileToUpload = EncodingUtil.urlDecode(fileToUpload, 'UTF-8');

        filenm = EncodingUtil.urlEncode(filenm , 'UTF-8'); // encode the filename in case there are special characters in the name 
        String filename = 'Storage' + '/' + filenm ;
        String attachmentBody = fileToUpload;

        String formattedDateString = DateTime.now().formatGMT('EEE, dd MMM yyyy HH:mm:ss z');




        // s3 bucket!
        String key = '**********' ;
        String secret = '********' ;
        String bucketname = 'testbucket' ;
        String region = 's3-us-west-2' ;



        String host = region + '.' + 'amazonaws.com' ; //aws server base url




    try{
        HttpRequest req = new HttpRequest();
        http = new Http() ;
        req.setMethod('PUT');
        req.setEndpoint('https://' + bucketname + '.' + host +  '/' +  filename );
        req.setHeader('Host', bucketname + '.' + host);

        req.setHeader('Content-Encoding', 'UTF-8');
        req.setHeader('Content-Type' , doctype);
        req.setHeader('Connection', 'keep-alive');
        req.setHeader('Date', formattedDateString);
        req.setHeader('ACL', 'public-read-write');


        String stringToSign = 'PUT\n\n' +
                doctype + '\n' +
                formattedDateString + '\n' +
                '/' + bucketname +  '/' + filename;


        Blob mac = Crypto.generateMac('HMACSHA1', blob.valueof(stringToSign),blob.valueof(secret));
        String signed = EncodingUtil.base64Encode(mac);
        String authHeader = 'AWS' + ' ' + key + ':' + signed;
        req.setHeader('Authorization',authHeader);

        req.setBodyAsBlob(EncodingUtil.base64Decode(fileToUpload)) ;



        HttpResponse response = http.send(req);

        Log.debug('response from aws s3 is ' + response.getStatusCode() + ' and ' + response.getBody());


    }catch(Exception e){
            Log.debug('error in connecting to s3 ' + e.getMessage());
            throw e ;
        }
    }

Juned Ahsan

The AWS SDK for Java exposes a high-level API, called TransferManager, that simplifies multipart uploads (see Uploading Objects Using Multipart Upload API). You can upload data from a file or a stream. You can also set advanced options, such as the part size you want to use for the multipart upload, or the number of concurrent threads you want to use when uploading the parts. You can also set optional object properties, the storage class, or the ACL. You use the PutObjectRequest and the TransferManagerConfiguration classes to set these advanced options.

Here is the sample code from https://docs.aws.amazon.com/AmazonS3/latest/dev/HLuploadFileJava.html.

You can adapt to your Salesforce Apex code:

import com.amazonaws.SdkClientException;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
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;

public class HighLevelMultipartUpload {

    public static void main(String[] args) throws Exception {
        Regions clientRegion = Regions.DEFAULT_REGION;
        String bucketName = "*** Bucket name ***";
        String keyName = "*** Object key ***";
        String filePath = "*** Path for file to upload ***";

        try {
            AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
                    .withRegion(clientRegion)
                    .withCredentials(new ProfileCredentialsProvider())
                    .build();
            TransferManager tm = TransferManagerBuilder.standard()
                    .withS3Client(s3Client)
                    .build();

            // TransferManager processes all transfers asynchronously,
            // so this call returns immediately.
            Upload upload = tm.upload(bucketName, keyName, new File(filePath));
            System.out.println("Object upload started");

            // Optionally, wait for the upload to finish before continuing.
            upload.waitForCompletion();
            System.out.println("Object upload complete");
        } catch (AmazonServiceException e) {
            // The call was transmitted successfully, but Amazon S3 couldn't process 
            // it, so it returned an error response.
            e.printStackTrace();
        } catch (SdkClientException e) {
            // Amazon S3 couldn't be contacted for a response, or the client
            // couldn't parse the response from Amazon S3.
            e.printStackTrace();
        }
    }
}

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

Upload file to S3 Bucket using HTTP POST

分類Dev

-AWS C# .Net Core- How to upload a .jpg image to S3 bucket without saving it as a file

分類Dev

Checking if file is larger than 1 MB

分類Dev

How to setup aws-sdk to get file content from a public file in s3 bucket?

分類Dev

amazon s3, upload file in folder in bucket

分類Dev

amazon s3, upload file in folder in bucket

分類Dev

S3 direct bucket upload: success but file not there

分類Dev

How to read csv file from s3 bucket in AWS Lambda?

分類Dev

How do I delete a versioned bucket in AWS S3 using the CLI?

分類Dev

R - How to copy and paste files from one location to another within an s3 bucket (using aws.s3)?

分類Dev

How to automate permissions for AWS s3 bucket objects

分類Dev

How to synchronously upload files to S3 using aws-sdk?

分類Dev

Polling S3 Bucket for file using Spring integration

分類Dev

Is there way to get the original url name of the file that I upload on s3 bucket

分類Dev

How to properly upload an object to AWS S3?

分類Dev

salesforce apexを使用して大きなファイル(12 MBを超える)をawss3バケットにアップロードする方法

分類Dev

List contents of AWS S3 bucket

分類Dev

AWS LastModified S3 Bucket different

分類Dev

How to upload a file to S3 without a name

分類Dev

My Web Service throws an System.AggregateException when I upload files larger than 2MB to SharePoint Online

分類Dev

How to copy a file with spaces in its file name from one bucket to the other using AWS CLI (Dos)

分類Dev

Upload file (> 4MB) to OneDrive using Graph API

分類Dev

How to point a Netlify subdomain to an AWS S3 bucket via CNAME?

分類Dev

How to fetch the bucket region and pass it to client o generate the presigned URLS aws s3

分類Dev

Terraform for AWS: How to have multiple events per S3 bucket filtered on object path?

分類Dev

How to upload 2+ MB file into xampp MySQL via phplocalmyadmin?

分類Dev

Using AWS (S3) via jclouds - how to assume role

分類Dev

How can I know what s3 bucket serverless is using for deploying?

分類Dev

How to do a Pre-signed POST upload to AWS S3 in Go?

Related 関連記事

  1. 1

    Upload file to S3 Bucket using HTTP POST

  2. 2

    -AWS C# .Net Core- How to upload a .jpg image to S3 bucket without saving it as a file

  3. 3

    Checking if file is larger than 1 MB

  4. 4

    How to setup aws-sdk to get file content from a public file in s3 bucket?

  5. 5

    amazon s3, upload file in folder in bucket

  6. 6

    amazon s3, upload file in folder in bucket

  7. 7

    S3 direct bucket upload: success but file not there

  8. 8

    How to read csv file from s3 bucket in AWS Lambda?

  9. 9

    How do I delete a versioned bucket in AWS S3 using the CLI?

  10. 10

    R - How to copy and paste files from one location to another within an s3 bucket (using aws.s3)?

  11. 11

    How to automate permissions for AWS s3 bucket objects

  12. 12

    How to synchronously upload files to S3 using aws-sdk?

  13. 13

    Polling S3 Bucket for file using Spring integration

  14. 14

    Is there way to get the original url name of the file that I upload on s3 bucket

  15. 15

    How to properly upload an object to AWS S3?

  16. 16

    salesforce apexを使用して大きなファイル(12 MBを超える)をawss3バケットにアップロードする方法

  17. 17

    List contents of AWS S3 bucket

  18. 18

    AWS LastModified S3 Bucket different

  19. 19

    How to upload a file to S3 without a name

  20. 20

    My Web Service throws an System.AggregateException when I upload files larger than 2MB to SharePoint Online

  21. 21

    How to copy a file with spaces in its file name from one bucket to the other using AWS CLI (Dos)

  22. 22

    Upload file (> 4MB) to OneDrive using Graph API

  23. 23

    How to point a Netlify subdomain to an AWS S3 bucket via CNAME?

  24. 24

    How to fetch the bucket region and pass it to client o generate the presigned URLS aws s3

  25. 25

    Terraform for AWS: How to have multiple events per S3 bucket filtered on object path?

  26. 26

    How to upload 2+ MB file into xampp MySQL via phplocalmyadmin?

  27. 27

    Using AWS (S3) via jclouds - how to assume role

  28. 28

    How can I know what s3 bucket serverless is using for deploying?

  29. 29

    How to do a Pre-signed POST upload to AWS S3 in Go?

ホットタグ

アーカイブ