0

I'm working with a lightning custom component that needs to load files and handle them in back controller.

I have this definition of lightning:input:

<lightning:input type="file" label="{!$Label.c.TM_FirmaEvidencia}" multiple="false" onchange="{!c.handleFileChange}"/>

And this controller.js function:

handleFileChange : function(component, event, helper){
    var files = event.getSource().get("v.files");
    console.log(JSON.stringify(files));
    debugger;
},

But it's always giving me the following console:

{"0":{}}

No matter what type of document I'm trying to load (even thought I'm not surpasing the size limits) it doesn't appear to work.

Does anyone know what may be causing this?

5

JSON.stringify will not work on files (Blob type). You should instead use FileReader. You can check some of sample code here

You can use below to understand better:

handleFileChange : function(component, event, helper){
    var files = event.getSource().get("v.files");
    console.log(JSON.stringify(files));
    console.log(event.getSource().get("v.files")[0]);

    let reader = new FileReader();
    reader.readAsText(event.getSource().get("v.files")[0]);

    reader.onload = function() {
        console.log(reader.result);
    };

    reader.onerror = function() {
        console.log(reader.error);
    };
}

You can test it by uploading text file.

Output:

enter image description here

  • Thanks a lot! That's exactly what I needed! – molinet Aug 21 '19 at 12:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.