Lightning Input Type File : Aura v/s LWC
Aura Component
Aura Component : HTML
    
                      
    
        
             
 
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)
     
        
              
                   
 
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
    45.0 
    true 
    
        lightning__RecordPage 
        lightning__AppPage 
        lightning__HomePage 
        lightningCommunity__Page 
     
 
 
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 leads = new List();
   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 cvList=new List();
        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
 
Hi
ReplyDeleteI 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.
Thank For sharing Valuable Information
ReplyDeletesalesforce cpq training
salesforce cpq online training