3

I need to input a CSV file using <input type='file'> from an Lightning Component and pass it to an Apex Controller for further processing.

Component

<input type="file"  aura:id="file-upload-input" id="file-upload" class="slds-file-selector__input slds-assistive-text" onchange="{!c.fileSelected}"/>

JS Controller

fileSelected : function(component, event, helper) {
    var fileInput = component.find("file-upload-input").getElement();
    var file = fileInput.files[0];
    console.log('file'+file);
    var action = component.get("c.passFile");
    action.setParams({ file : file } );

    action.setCallback(this, function(actionResult) {
        console.log((actionResult.getReturnValue()));
        // component.set("v.emailStr", actionResult.getReturnValue());     
    });
    $A.enqueueAction(action);
}

Apex Controller

@AuraEnabled
public static void passFile(Blob file)
{
    System.debug('Inside Apex');
    System.debug('file'+file);
}

This gives an Salesforce Internal Error

1 Answer 1

7

You can't pass a Blob type to an apex controller method. You'll have to encode the file in your Javascript method, then decode it in your apex controller like this:

Lightning controller

var reader = new FileReader();
var self = this;
reader.onload = function () {
     action.setParams({ file : encodeURIComponent(reader.result) } );
     action.setCallback(self, function(actionResult) {
         console.log((actionResult.getReturnValue()));
         // component.set("v.emailStr", actionResult.getReturnValue());     
     });
     $A.enqueueAction(action);
};
reader.readAsDataURL(file);

Apex controller

String myFile = EncodingUtil.urlDecode(file, 'UTF-8');
2
  • Why the delete?
    – Adrian Larson
    Commented Jun 26, 2017 at 11:47
  • @AdrianLarson Because I was missing a part :) Commented Jun 26, 2017 at 12:04

You must log in to answer this question.

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