2

I have a requirement to upload the file in lightning component and sending it to third party without saving it in salesforce, so I am using below code for it ( tried as well, but did not work)

<lightning:input aura:id="fileId" accept= '.msf'
                 onchange="{!c.validateAndContinue}" 
                 type="file" 
                 name="file" 
                 label="Upload" 
                 multiple="false"/>                                                

and in controller.js, to read the content using the below code:

    validateAndContinue : function(component, event, helper) {
                           if (event.getSource().get("v.files").length > 0) {
                            var objFileReader = new FileReader();
                            fileName = event.getSource().get("v.files")[0]['name'];
                            objFileReader.onload = $A.getCallback(function() {
                             alert('hi');
                             var fileContents = objFileReader.result;
                           });
                           }
                           }

The issue is that callback method is not getting invoked, so not able to read the content of file. Do anyone have clue or have faced similar kind of issue. Thanks in advance.

P.S: This lightning component is for customer community.

1 Answer 1

4

You didn't actually read the file. You need to call one of readAsArrayBuffer, readAsBinaryString, readAsDataURL, or readAsText. You should call one of those methods after setting your onload handler. You can read more about the FileReader on MDN.

5
  • Thanks @sfdcfox for your quick response. I got your point. So, ideally I should have used below code to read content. objFileReader.onload = $A.getCallback(function() { alert('hi'); var content = objFileReader.readAsText(file); } but noticed that callback is not getting executed. alert message is not coming up. Aug 21, 2018 at 20:21
  • 1
    @ArpitSethi The method you choose to call must be outside of your callback. objFileReader.onload = $A.getCallback(function() { alert('hi'); var content = objFileReader.result; }); objFileReader.readAsText(file);
    – sfdcfox
    Aug 21, 2018 at 20:24
  • I need to pass uploaded file's content as a blob in apex class method, what should I use, readAsText() ? Aug 21, 2018 at 20:51
  • @ArpitSethi I used readAsDataURL, which gives you a nice base-64 encoded string to work with. But if you know it's plain text, that works, too.
    – sfdcfox
    Aug 21, 2018 at 20:54
  • Thanks a lot @sfdcbox. readAsDataURL works for me. Cheers !!! Aug 21, 2018 at 21:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .