Lightning Input Type File : Aura v/s LWC


Aura Component

Aura Component : HTML


<aura:component description="FileUploaderFromAuraComponent" controller="FileUploadController">
    <aura:attribute name="fileToBeUploaded" type="Object[]"/>
    <aura:attribute name="isLoading" type="boolean" default="false"/>
    <aura:attribute name="lead" type="Lead" default="{'sobjectType':'Lead','FirstName':'Test','LastName':'Lead','Company':'IBM','Email':'testLead@gmail.com'}"/>
    <aura:if isTrue="{!v.isLoading}">
             <lightning:spinner aura:id="mySpinner"/>             
    </aura:if>        
    <div class=" slds-box">
        <div class="slds-grid slds-wrap">
            <lightning:input aura:id="file-input" type="file"
                             files="{!v.fileToBeUploaded}"
                             onchange="{!c.onFileUploaded}"
                             accept="image/png,image/jpg,image/jpeg"
                             label="Attachment/File"
                             name="file" multiple="false"/>
        </div>
    </div>
</aura:component>



Aura Component : Controller JS


({
    onFileUploaded:function(component,event,helper){
        helper.show(component,event);
        var files = component.get("v.fileToBeUploaded");
        if (files && files.length > 0) {
            var file = files[0][0];
            var reader = new FileReader();
            reader.onloadend = function() {
                var dataURL = reader.result;
                var content = dataURL.match(/,(.*)$/)[1];
                helper.upload(component, file, content, function(answer) {
                    helper.hide(component,event);
                    if (answer=='Success') {                        
                    }else{
                        var toastEvent = $A.get("e.force:showToast");
                        toastEvent.setParams({
                             "title": "Error!",
                             "type":"Error",
                             "message": "File Failed to upload..."
                        });
                        toastEvent.fire();
                    }
                });
            }
            reader.readAsDataURL(file);
        }
        else{
            helper.hide(component,event);
        }
    }
})



Aura Component : Helper JS


({
    upload: function(component, file, base64Data, callback) {
        var lead=component.get("v.lead");
        var action = component.get("c.saveParentAsLead");
        console.log('type: ' + file.type);
        action.setParams({
            ld:lead,
            strFileName: file.name,
            base64Data: base64Data,
        });
        action.setCallback(this, function(a) {
            var state = a.getState();
            if (state === "SUCCESS") {
                callback(a.getReturnValue());
            }
        });
        $A.enqueueAction(action);
    },
    show: function (cmp, event) {
        component.set("v.isLoading", true);
    },
    hide:function (cmp, event) {
        component.set("v.isLoading", false);
    }
})


Lightning Web Component

LWC : Template (HTML)


<template>
     <lightning-card title="LOCAL MATTERS SIGNUP" icon-name="custom:custom3">
        <div class="slds-m-around_medium">
              <div>
                  <lightning-input onchange={handleFileUploaded} name="uploadFile" label="Attachment/File" accept="image/png,image/jpg,image/jpeg"></lightning-input>
                  <div class="slds-text-body_small slds-text-color_error">{fileName}</div>
              </div> 
              <template if:true={isLoading}>
                  <lightning-spinner alternative-text="Loading"></lightning-spinner>
              </template>
        </div>
     </lightning-card>
</template>



Lightning Web Component : JS


import {
    LightningElement,
    track
} from 'lwc';

export default class FileUploadComponent extends LightningElement {
    @track isLoading = false;
    MAX_FILE_SIZE = 5000000; //Max file size 5.0 MB
    filesUploaded = [];
    file;
    fileContents;
    fileReader;
    content;
    handleFileUploaded(event) {
        if (event.target.files.length > 0) {
            this.filesUploaded = event.target.files;
            this.fileName = event.target.files[0].name;
            this.file = this.filesUploaded[0];
            if (this.file.size > this.MAX_FILE_SIZE) {
                this.fileName = 'File Size is to long. File size should be less then 5MB';
            } else {
                this.handleUpload();
            }
        }
    }
    handleUpload() {
        if (this.filesUploaded.length > 0) {
            this.isLoading = true;
            this.file = this.filesUploaded[0];
            // create a FileReader object 
            this.fileReader = new FileReader();
            // set onload function of FileReader object  
            this.fileReader.onloadend = (() => {
                    this.fileContents = this.fileReader.result;
                    let base64 = 'base64,';
                    this.content = this.fileContents.indexOf(base64) + base64.length;
                    this.fileContents = this.fileContents.substring(this.content);


                    const lead = {
                        FirstName: "Test",
                        LastName: = "Lead",
                        Company: "IBM",
                        Email: "testlead@gmail.com"
                    };

                    // eslint-disable-next-line no-console
                    console.log('Current value of the input for Lead Object: ', fields);
                    saveParentAsLead({
                            ld: lead,
                            strFileName: this.fileName,
                            base64Data: encodeURIComponent(this.fileContents)
                        })
                        .then(msg => {
                                // eslint-disable-next-line no-console
                                console.log("Message from Server :", msg);
                                this.isLoading = false;
                                if (msg === 'Success') {
                                    this.dispatchEvent(
                                        new ShowToastEvent({
                                            title: 'Lead',
                                            message: 'File is Successfully uploaded as Child of Lead Record',
                                        }),
                                    );
                                }
                            } else {
                                this.dispatchEvent(
                                    new ShowToastEvent({
                                        title: 'Error creating record',
                                        message: msg,
                                        variant: 'error',
                                    }),
                                );
                            }
                        }).catch(error => {
                    this.isLoading = false;
                    // eslint-disable-next-line no-console
                    console.log('error ', error);
                    this.dispatchEvent(
                        new ShowToastEvent({
                            title: 'Error creating record',
                            message: error.body.message,
                            variant: 'error',
                        }),
                    );
                });
            });
        this.fileReader.readAsDataURL(this.file);
    } else {
        this.isLoading = false;
        this.fileName = 'Please select file to upload!!';
    }
}
}



Lightning Web Component : XML


<!--xml version="1.0" encoding="UTF-8"?-->
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="RegistrationWebComponent">
    <apiVersion>45.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
        <target>lightning__AppPage</target>
        <target>lightning__HomePage</target>
        <target>lightningCommunity__Page</target>
    </targets>
</LightningComponentBundle>


Note : Both framework used same apex class
Aura and LWC : Apex Class


public with sharing class FileUploadController{
    @AuraEnabled
    public static String saveParentAsLead(Lead ld, String strFileName, String base64Data) {
    try {
   List<Lead> leads = new List<Lead>();
   leads.add(ld);
   Database.SaveResult[] srList = Database.insert(leads, false);
   // Iterate through each returned result
   for (Database.SaveResult sr : srList) {
    if (sr.isSuccess()) {
     // Operation was successful, so get the ID of the record that was processed
     System.debug('Successfully inserted Lead. Lead ID: ' + sr.getId());
     return saveFile(sr.getId(),strFileName,base64Data);
    }else {
     return 'Failed';
    }
   }                
    } catch (DmlException ex) {
   return 'Failed';
    }          
       return null;
    }
    public static string saveFileForLead(Id idParent, String strFileName, String base64Data) {
        // Decoding base64Data
        base64Data = EncodingUtil.urlDecode(base64Data, 'UTF-8');        
        // inserting file
        ContentVersion cv = new ContentVersion();
        //cv.ContentLocation = 'S';
        cv.Title = strFileName;
        cv.PathOnClient = '/' + strFileName;
        cv.FirstPublishLocationId = idParent;
        cv.VersionData = EncodingUtil.base64Decode(base64Data);
        cv.IsMajorVersion = true;
        List<ContentVersion> cvList=new List<ContentVersion>();
        cvList.add(cv);
        Database.SaveResult[] srList = Database.insert(cvList, false);
        // Iterate through each returned result
        for (Database.SaveResult sr : srList) {
            if (sr.isSuccess()) {
                // Operation was successful, so get the ID of the record that was processed
                return 'Success';
            }
            else {
                return 'Failed';
            }
        }
        return null;
    }  
}


Note: You can use this component for file is less then or Equal to 5 MB. After save whole code you will drag and drop code into Lightning Record Detail Page

Happy Sharing...

Everyone has their own favourites, so please feel free to share yours in the comments below!

Comments

  1. Hi
    I want to change the text Uploade files or drop files to Attach file in lightning input type file how i can do it.
    Thanks in adv.

    ReplyDelete

Post a Comment

Popular posts from this blog

Salesforce LWC : Compact Layout on Hover

Salesforce LWC With Third Party JS : D3

Communications between Lightning Components : Salesforce