Getting 'Cannot read property 'getElement' of undefined' in my jscript - Answers - Salesforce Trailblazer Community
Trailblazer Community
Ask Search:
Khizer HussainKhizer Hussain 

Getting 'Cannot read property 'getElement' of undefined' in my jscript

Hello Everyone,


I have a lightning component for drag and drop functionality which should invoke a post callout in apex class and the file should get saved in a external DB . However when i try to upload a file, I am getting the fllowing error.

 

User-added image


Action failed: c:Classfileupload$controller$handleFilesChange [Cannot read property 'getElement' of undefined]
Failing descriptor: {c:Classfileupload$controller$handleFilesChange}

 


The following is my component:
<aura:component controller="Classfileupload" implements="force:appHostable,lightning:availableForFlowScreens,force:hasRecordId,force:lightningQuickAction" access="global">
 <!-- 'parentId' Aura Attribute for store the Id for Parent Record where we are attach our file -->  
   <aura:attribute name="recordId" type="String"/>
 <!-- 'showLoadingSpinner' attribute for show/hide the uploading image and msg in aura:if-->
   <aura:attribute name="showLoadingSpinner" type="boolean" default="false" />
 <!-- 'fileName' attribute for display the selected file name -->  
   <aura:attribute name="fileName" type="String" default="No File Selected.." />
 <!-- Lightning Input with file type and on file change call the 'handleFilesChange' controller -->
    <aura:attribute name="jobID" type="String"/>
    <!-- fetches the jobID from the record -->
 
   <lightning:input aura:id="fileId" onchange="{!c.handleFilesChange}" type="file" name="file" label="Upload Attachment" multiple="false"/>
   <div class="slds-text-body_small slds-text-color_error">{!v.fileName} </div>
 
 <!--use aura:if for show-hide the loading spinner image--> 
   <aura:if isTrue="{!v.showLoadingSpinner}">
      <div class="slds-text-body_small slds-text-color_error">Uploading... 
         <img src="/auraFW/resources/aura/images/spinner.gif" class="spinner-img" alt="Loading"/>'
      </div>
   </aura:if>
   
 <br/>
    <lightning:button aura:id="submit" type="button" class="submit" onclick="{!c.doSave}">Upload Attachment</lightning:button>
</aura:component>
 
The following is my .js file
({
    doSave: function(component, event, helper) {
        var fileInput  = component.find("file").getElement();
        var file = fileInput.files[0];
        console.log('file is coming==>'+file);
 
        var reader = new FileReader();
   
        reader.onload = function (e) {
            var fileContent = reader.result;
            var base64 = 'base64,';
            var dataStart = fileContent.indexOf(base64) + base64.length;
            fileContent = fileContent.substring(dataStart)
            console.log(fileContent);
            
            var jobID = component.get("v.jobID");
            var recordId = component.get("v.recordId");
            
            var action = component.get("c.POST");
            action.setParams({ file : fileContent, jobID : jobID });
             action.setCallback(this, function(response) {
                var returnValue = response.getReturnValue();
                console.log('returnValue===>'+returnValue);
            
                component.set("v.message", returnValue);
            });
            $A.enqueueAction(action);
        };
        reader.readAsDataURL(file);
        
        var toastEvent = $A.get("e.force:showToast");
        toastEvent.setParams({
            mode: 'sticky',
            message: 'Success',
            messageTemplate: '{0} record created! See it {1}!',
            messageTemplateData: ['Job', {
                url: 'https://csv-file-upload.herokuapp.com/leads/' + jobID,
                label: 'here',
                }
            ]
        });
        toastEvent.fire();
    },
 
    handleFilesChange: function(component, event, helper) {
        
        var input = component.find("file").getElement();
        input.handleFilesChange();
        
        var action = component.get("c.createJob");
        action.setCallback(this, function(response) {
                var returnValue = response.getReturnValue();
                console.log(returnValue);
                
                component.set("v.recordId", returnValue[0]);
                component.set("v.jobID", returnValue[1]);
            });
            $A.enqueueAction(action);
        
        window.setTimeout(
            $A.getCallback(function() {
                $A.util.removeClass(component.find('previewContainer'),"slds-hide");
            }), 5000
        )
    },
 
})


 
The following is my apex class:
 
public with sharing class Classfileupload {
 
 @AuraEnabled
    public static List<String> createJob() {
        
        List<String> myList = new List<String>();
          DMS__c dms = new DMS__c(Name='Amtex Demo3',Description__c='Test',Folder__c='Active',Key_Words__c='Test');
        insert dms;
         Id recordId = dms.Id;
      
        DMS__c recdms = [SELECT id, JobID__c, id_reference__c FROM DMS__c WHERE id = :recordId];
       
        update recdms;
        
        myList.add(recordId);
        myList.add(recdms.JobID__c);
        system.debug('ID LIST: ' + myList);
        return myList;
    }
    
    @AuraEnabled
    public static String POST(Blob file, String jobID, String fileName) {
        
        Http h = new Http();
        String url = 'https://csv-file-upload.herokuapp.com/leads/' + jobID;
        String separationString = 'da5cbc76-39ba-4f80-8b81-090b82e90cf0';
        String str = file.toString();
   //     String csvBody = EncodingUtil.base64Encode(csvBlob);
        // decode 
        Blob decodedBlob = EncodingUtil.base64Decode(str);
        system.debug('string ==>'+decodedBlob);
        // convert to string
        String result = decodedBlob.toString();
        
        // assemble the body payload
        String header = '--' + separationString + '\nContent-Disposition: form-data; name="file"; filename="' + fileName + '"\nContent-Type: application/octet-stream\n\n';
        //String body = EncodingUtil.base64Encode(file) + '\n';
        String body = result + '\n';
        String footer = '--' + separationString + '--';
        String bodyPayload = header + body + footer;
        system.debug('PAYLOAD: ' + bodyPayload);
 
        HttpRequest req = new HttpRequest();
        req.setHeader('Content-Type', 'multipart/form-data; boundary=' + separationString);
        
        req.setEndpoint(url);
        req.setMethod('POST');
        req.setBody(bodyPayload);
        system.debug('REQUEST: ' + req);
 
        // Send the request, and return a response
        HttpResponse res = h.send(req);
        System.debug(res.getBody());
        return res.getBody();
    }
}

 


Please help me figure out what mistake is in this code and how to successfully get the file saved in external DB.

 

 

 

 

Amnon KruviAmnon Kruvi
Hi Khizer, 

You're using component.find("file"), but your file uploader's component I'd is "fileId". This means you're probably getting null from the find function, which would cause this error. 
Khizer HussainKhizer Hussain

Hey Amnon,

I made the changes. But still i am getting this error

[NoErrorObjectAvailable] Script error.
newErrorHandler()@https://static.lightning.force.com/ap16/auraFW/javascript/ozbOZt5SYUotl8he3imvcA/aura_proddebug.js:50227:14
errorHandlerWrapper()@https://static.lightning.force.com/ap16/auraFW/javascript/ozbOZt5SYUotl8he3imvcA/aura_proddebug.js:50243:25
K.dispatchEvent()@https://static.lightning.force.com/ap16/auraFW/javascript/ozbOZt5SYUotl8he3imvcA/aura_proddebug.js:8666:28
K.dispatchChangeEventWithDetail()@https://sukanta02-dev-ed.lightning.force.com/components/lightning/input.js:2:29721
K.dispatchChangeEvent()@https://sukanta02-dev-ed.lightning.force.com/components/lightning/input.js:2:32750
K.handleChange()@https://sukanta02-dev-ed.lightning.force.com/components/lightning/input.js:2:31512

Amnon KruviAmnon Kruvi
This appears to be a different error, so congratulations - you're making progress!
 Unfortunately, this stack trace doesn't give me anything I can work with. You'll want to use your browser's debugger, put a break point in your Javascript code, and trace what's crashing.