[SalesForce] How to upload data from csv file to custom object

I have this requirement to upload the records from a csv file and populate a custom object Course with fields Id, Name, Contact(Lookup detail), Fees and Date. This is the apex code I have:

public class importDataFromCSVController {
public Blob csvFileBody{get;set;}
public string csvAsString{get;set;}
public String[] csvFileLines{get;set;}
public List<Course__c> courlist{get;set;}
public importDataFromCSVController(){
    csvFileLines = new String[]{};
        courlist = New List<Course__c>(); 
}

public void importCSVFile(){
    try{
        csvAsString = csvFileBody.toString();
        csvFileLines = csvAsString.split('\n'); 

        for(Integer i=1;i<csvFileLines.size();i++){
            Course__c couObj = new Course__c();
            string[] csvRecordData = csvFileLines[i].split(',');
            couObj.name = csvRecordData[0] ;  
            couObj.id = csvRecordData[1];

            couObj.Contact__c = csvRecordData[2];
            String temp_fees=csvRecordData[3];
            couObj.Course_fees__c = Decimal.valueOf(temp_fees);
            String temp_date=csvRecordData[4];
            couObj.Course_Date__c = Date.parse(temp_date); 

            courlist.add(couObj);   
        }
        insert courlist;
    }
    catch (Exception e)

    {
        System.debug(e.getCause());
        ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured while importing data. Please make sure input csv file is correct');
        ApexPages.addMessage(errorMessage);
    }  
}

}

The record I am trying to enter is:

enter image description here

and the Visualforce code :

<apex:page controller="importDataFromCSVController">
<apex:form >
    <apex:pagemessages />
    <apex:pageBlock >
        <apex:pageBlockSection columns="5"> 
              <apex:inputFile value="{!csvFileBody}"  filename="{!csvAsString}"/>
              <apex:commandButton value="Import Account" action="{!importCSVFile}"/>
        </apex:pageBlockSection>
    </apex:pageBlock>
    <apex:pageBlock >
       <apex:pageblocktable value="{!courList}" var="cours">
          <apex:column value="{!cours.Id}" />
          <apex:column value="{!cours.Name}" />
          <apex:column value="{!cours.Contact__c}" />
          <apex:column value="{!cours.Course_fees__c}" />
          <apex:column value="{!cours.Course_Date__c}" />
    </apex:pageblocktable>
 </apex:pageBlock>

I am fairly new to coding, so if anyone can correct what I am doing, it would be very much appreciated.

The error I am getting is:

An error has occured while importing data. Please make sure input csv file is correct

This error is the custom error message provided in the catch block.

Best Answer

I had the same problem but when I changed parse with valueOf everything was fine. The passed date format was wrong.

Try this

couObj.Course_Date__c = Date.valueOf(temp_date);