1

I am integrating AWS with salesforce now I try to upload the file to AWS S3 Server from salesforce, But I am facing the error after uploading the file as "Error while uploading file to AWS. Please contact administrator. Exceeded max size limit of 6000000 with request size 6004736"

Aura Component: {

<lightning:card footer="" title="Upload File to AWS">
    <aura:set attribute="actions">
        <div class="slds-grid">
            <div class="slds-col slds-p-bottom_medium type">
                <lightning:select aura:id="select1" class="select">
                                <option value="Enrollment Materials">Enrollment Materials</option>
                    <option value="Notices &amp; Disclosures">Notices &amp; Disclosures</option> 
                </lightning:select>
            </div>
            <div class="slds-col slds-p-left_xx-small fileupload">
                <lightning:fileUpload label="Upload New File"
                                      name="fileUploader"
                                      multiple="true"
                                      recordId="{!v.recordId}"
                                      onuploadfinished="{!c.handleUploadFinished}" />
            </div>
        </div>
     </aura:set>

}

JS code: { handleUploadFinished: function (cmp, event, helper) { // Get the list of uploaded files cmp.set("v.showLoading", true); helper.uploadFinish(cmp, event, helper, 0);// change last attribute as per condition

},

}

JS Helper: { uploadFinish: function (cmp, event, helper, index) {

        // Get the list of uploaded files
        console.log('########################uploadFinish#####################');
        var uploadedFiles = event.getParam("files");
        console.log('uploadedFiles---', uploadedFiles);
        var docType = cmp.find("select1").get("v.value");
        console.log("type====>",docType);

        cmp.set("v.showLoading", true);
        var action = cmp.get("c.uploadFileToAWS");
        action.setParams({
            "recordId": cmp.get("v.recordId"),
            "contentDocumentId": uploadedFiles[index].documentId,
            "fileName": uploadedFiles[index].name,
            "docType":docType
        });
        action.setCallback(this, function(response) {

            var state = response.getState();
            if (state === "SUCCESS") {
                if((uploadedFiles.length-1) == index) {
                    helper.getData(cmp, event, helper);
                    cmp.set("v.showLoading", false);
                } else {
                    index = index + 1;
                    helper.uploadFinish(cmp, event, helper, index);
                }

            } else {
                cmp.set("v.showLoading", false);
                var errors = response.getError();
                 var toastEvent = $A.get("e.force:showToast");
                 if (errors) {
                     if (errors[0] && errors[0].message) {
                         console.log("Error message: " +
                                  errors[0].message);

                                  var toastEvent = $A.get("e.force:showToast");
                                      toastEvent.setParams({
                                          title : 'Error!!',
                                          message:'Error while uploading file to AWS. Please contact administrator.' + errors[0].message,
                                          duration:' 5000',
                                          key: 'info_alt',
                                          type: 'error',
                                          mode: 'pester'
                                      });
                                      toastEvent.fire();
                    }
                }

            }

        });
        $A.enqueueAction(action);
    }

}

Apex ctrl: {

@AuraEnabled
public static Boolean uploadFileToAWS(String contentDocumentId, String recordId, String fileName, String docType) {
    //String docTypeEncoded = EncodingUtil.urlEncode(docType, 'UTF-8');
    System.debug('doctype----->'+docType);
    List<CustomUser__c> cUsers  = [SELECT AWS_Folder_Name__c, randomkey__c,BucketRegion__c,BucketName__c FROM CustomUser__c WHERE id= :RecordId LIMIT 1];
    if(cUsers.size() == 0) {
        throw new AuraHandledException('SYSTEM ERROR : NO such record exists');
    }
    
    List<ContentVersion> contentVersions = [select VersionData from ContentVersion where ContentDocumentId = :contentDocumentId];
    if(contentVersions.size() > 0) {
        //fileName = Connector.canonicalUriFor(fileName);
        //fileName = EncodingUtil.urlEncode(fileName, 'UTF-8');
        HttpResponse res = AWSURLCtrl.uploadContent(cUsers.get(0).BucketRegion__c, cUsers.get(0).BucketName__c, EncodingUtil.urlEncode(cUsers.get(0).AWS_Folder_Name__c, 'UTF-8'), contentVersions.get(0).VersionData, EncodingUtil.urlEncode(fileName, 'UTF-8'), EncodingUtil.urlEncode(docType, 'UTF-8'));
        System.debug('a---->'+res);
        List<AWS_file_Details__c> currentLatest=[SELECT Id,VersionNumber__c,IsLatest__c,PreviousVersion__r.Id from AWS_file_Details__c WHERE Custom_User__r.Id=:cUsers.get(0).Id AND File_Path__c=:fileName AND IsLatest__c=true  LIMIT 1];
        AWS_file_Details__c latest=new AWS_file_Details__c();
        
        
        AWS_file_Details__c fileDetail=new AWS_file_Details__c();
        fileDetail.File_Path__c=fileName;
        fileDetail.Custom_User__c=cUsers.get(0).Id;
        fileDetail.VersionId__c=res.getHeader('x-amz-version-id');
        fileDetail.Document_Type__c=docType;
        if(currentLatest!=null && currentLatest.size()==1) {
            latest.Id=currentLatest.get(0).Id;
            fileDetail.VersionNumber__c=currentLatest.get(0).VersionNumber__c+1;
            fileDetail.IsLatest__c=true;
            fileDetail.PreviousVersion__c=latest.Id;
            insert fileDetail;
            latest.IsLatest__c=false;
            update latest;
        } else {
            fileDetail.VersionNumber__c=1;
            fileDetail.IsLatest__c=true;
            insert fileDetail;
        }
        delete [select Id from ContentDocument where Id=:contentDocumentId];
    }
    return false;
}

}

Apex Method: {

public static HttpResponse uploadContent(String region, String bucketName ,String current_user, Blob blobToUpload, String fileName, String docType) {
    String access = KeyValueHelper.getTextValue('AWSAccessKey');
    String secret = KeyValueHelper.getTextValue('AWSSecretKey');
    Connector connector = new Connector(access, secret);
    S3 s = new S3(connector,region);
    S3.Bucket b = s.bucket(bucketName);
    //fileName=fileName.replaceAll(' ','%20');
    HttpResponse res=connector.s3(region).bucket(bucketName).createContent(current_user + '/' + docType + '/' +fileName, new Map<String, String>(), blobToUpload);
    //system.debug('response after upload @@@@@@@@@@@@'+res.getHeader('x-amz-version-id'));
    return res;
}

}

Please help me to find solution on that

2
  • 3
    Including code as images is not encouraged. It makes it hard to read and forces people to manually type it out if they want to try to reproduce an issue. Please edit your question to include the code as text instead (the {} button formats text as a code block).
    – Derek F
    Oct 1, 2020 at 12:34
  • 2
    Getting around the 6MB heap limit means you'll need to find a way to chunk the request, or pull the contents into your component using Javascript (client-side) code alone.
    – Derek F
    Oct 1, 2020 at 12:36

1 Answer 1

2

Instead of doing it from Apex, I have written an Aura Component that can do it directly from the browser:

https://github.com/banderson5144/sfs3upload/tree/master/force-app/main/default

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.