Thursday, July 1, 2021

How to restrict file size limit in Lightning file upload

This Post explains how to restrict file size limit with standard Lightning file upload in lightning component. Below is the demo of output :

Restrict file size Lightning file upload


The maximum limit of file in lightning file upload is 2 GB, but what if you want to restrict the file size less than 2 GB, Like 10 MB or 100 MB. So for that you have to write a small method in apex to achieve it. Below is the code for restrict file size up to 10 MB:

UploadFile.cmp :


<aura:component controller="RestrictFileUploadSize" implements="flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId" access="global">
    <aura:attribute name="documents" type="object[]"/>
    
    <div class="slds-grid" style = "background-color:white; padding-left: 15%; padding-bottom: 8%;">
        <div class=" slds-col slds-large-size_2-of-12 slds-medium-size_3-of-12 slds-small-size_4-of-12 slds-p-top_large">
            Add Attachment:
        </div>
        <div class="slds-col bccolor slds-m-top_medium slds-large-size_10-of-12 slds-medium-size_9-of-12 slds-small-size_6-of-12 orient">
            
            <div class="slds-grid slds-wrap" style="margin-left: 30px;">
                
                <lightning:fileUpload multiple="false"
                                      variant="label-hidden"
                                      recordId="{!v.recordId}"
                                      accept="['.pdf']"
                                      onuploadfinished="{!c.handleUploadFinished}"
                                      class="slds-m-bottom_small"/>
            </div>
            <span>Maximum size of a file: 10 MB</span>
            <aura:iteration items="{!v.documents}" var="document">
                <li>
                    <a id='{!document.documentId}'>{!document.Name}</a>
                </li>
            </aura:iteration>  
        </div>
    </div>
</aura:component>


UploadFile.js :


({    
    handleUploadFinished:function(component, event, helper){
        var uploadedFiles = event.getParam("files");
        var documentId = uploadedFiles[0].documentId;
        var action = component.get("c.contentSize");
        action.setParams({ cid : documentId });
        action.setCallback(this, function(response) {
            var state = response.getState();
            console.log('state--',state);
            if (state == "SUCCESS") {
                var tempList = response.getReturnValue();
                if(tempList == 'ERROR'){
                    var toastEvent = $A.get("e.force:showToast");
                    toastEvent.setParams({
                        "message": "File size can\'t be greater than 10 MB",
                        "type" : "Warning"
                    });
                    toastEvent.fire();
                }else{
                    var send = [];
                    var documentids = [];
                    send = component.get("v.documents");
                    for(var i = 0; i < uploadedFiles.length; i ++){
                        var documentId = uploadedFiles[i].documentId;
                        var fileName = uploadedFiles[i].name;
                        documentids.push(documentId);
                        var ca = {'Name':fileName, 'documentId':documentId};
                        send.push(ca);
                    }
                    component.set("v.documents", send);
                }
            }
        });
        $A.enqueueAction(action);
    }
})


RestrictFileUploadSize.apx :


public class RestrictFileUploadSize {
   @AuraEnabled
    public static String contentSize(String cid) {
        List<ContentDocument> Doc = [select id,contentsize from ContentDocument where id =: cid limit 1];
        integer size = Doc[0].contentsize;
        system.debug('size-->>'+size);
        if(size > 10485760){
            Delete Doc[0];
            return 'ERROR';
        }else{
            return 'SUCCESS';
        }
    }
}

  • Lightning file upload store the file in contentdocument object.
  • You can use contentsize field to restrict the size of file which store the size in byte.
  • Suppose you want to restrict the file size up to 50 MB, then convert 50 MB to byte and apply if condition to it. If uploaded file size is greater than your specified size then delete the document by id and show some error.


Thanks, 
Lovesalesforceyes




1 comment:

  1. Hi ,

    Thanks a lot for sharing your knowledge,

    I tried to use the same code , but made small changes
    1)Accepting multiple Files
    2) Changed the Apex Class , to Accept list of Files Id
    But it is showing error ? any Idea

    ReplyDelete

Get selected radio button value in LWC

This post explains how to get selected radio button in LWC. Below is demo of output : To use the radio button in LWC you have to use the  li...