+ Start a Discussion
Sai deep 13Sai deep 13 

if else loop not working during file upload in lightning component JS Controller ERROR:-[Cannot read property 'length' of null]

Component:-
<lightning:input aura:id="fuploader" type="file" name="file" label="Upload File" multiple="false" required="false"/>

JS Controller:-
({
    doSave : function(component, event, helper) {
        alert('Please wait for few seconds')
       
        if (component.find("fuploader").get("v.files").length > 0 ||component.find("fuploader").get("v.files").length !== NULL) {
                
        helper.uploadHelper(component, event);
            } else{
               alert('Hello');                 
    }
    }
})
Error:- This page has an error. You might just need to refresh it. Action failed: c:InclusionForm$controller$doSave [Cannot read property 'length' of null] Failing descriptor: {c:InclusionForm$controller$doSave



Thank You
Best Answer chosen by Sai deep 13
David Zhu 🔥David Zhu 🔥
component.find("fuploader").get("v.files") returns null if there is no file selected for <Lighting:input type="file"> component.
In the memory, it is expressed as null.length which results the error you see.

Once you selected a file for the component, component.find("fuploader").get("v.files").length will return a value.

You may modify the code to:

if (component.find("fuploader").get("v.files") != null)
 

All Answers

David Zhu 🔥David Zhu 🔥
component.find("fuploader").get("v.files") returns null if there is no file selected for <Lighting:input type="file"> component.
In the memory, it is expressed as null.length which results the error you see.

Once you selected a file for the component, component.find("fuploader").get("v.files").length will return a value.

You may modify the code to:

if (component.find("fuploader").get("v.files") != null)
 
This was selected as the best answer
Sai deep 13Sai deep 13
Hi David,
Thank you so much for Quick response

I have changed the code as you said above, it worked fine

Thanks and regards
Saideep