0

I created a custom CSV file upload functionality in lightning component. I am converting the CSV file as string from component controller and passing the string to apex controller (using file reader and readAsText). Then from controller spiting string into a list by occurence of /n.

var fileInput = component.find("file").getElement(); var file = fileInput.files[0]; var reader = new FileReader(); reader.readAsText(file, 'UTF-8');

The problem am facing here is,In some of the file /n is not coming on conversion of CVS to string. If I delete the last column of the file then it's working fine.

Component controller:

({
    handleUploadFinished : function(component, event, helper) {
        var fileInput = component.find("file").getElement();
        var file = fileInput.files[0];
        if(file.name.includes(".CSV") || file.name.includes(".csv")){
            if(file) {
                var reader = new FileReader();
                reader.readAsText(file, 'UTF-8');
                reader.onload = function(evt) {
                    var csv = evt.target.result;
                    console.log(csv);
                    component.set("v.csvString", csv);
                }
            }
        } else {
            helper.message(component,helper,"Please choose CSV file only","Error!");
            component.set("v.csvString", null);
            component.set("v.csvObject", null);
        }

    },

    UploadPointsLog : function(component, event, helper) {
        component.set("v.loading",true);
        var action = component.get('c.SaveRecords');
        action.setParams({
            csv_str : component.get("v.csvString")
        });
        action.setCallback(this, function(response) {
            var state = response.getState();
            if(state == "SUCCESS") {
                component.set("v.loading",false);
                var resp = response.getReturnValue();
                alert(resp);
            } else{
                component.set("v.loading",false);
                alert('error');
            }
        });
        $A.enqueueAction(action);
    }
})

Apex controller:

public class CSVCreator  {
    @AuraEnabled
    public static string SaveRecords(String csv_str){
        List<String> lines_raw = csv_str.split('\n');
        system.debug(lines_raw );
}
  • I would like to add two things. Firstly, Why you need to move the splitting logic into Apex, it could be done at js level itself, secondly, can you share the snap of excel, because it is difficult to analyze and one more thing you can also try, that if '/n ' is not coming you can split on other conditions, because some Delimeter would be coming which you can use to split on condition based. – Pranav Chitrans Dec 4 '19 at 5:08

Your Answer

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

Browse other questions tagged or ask your own question.