I have requirement where I have to read a CSV file. Using CSV file I have to insert a records in Salesforce after that I have to upload attachment in newly inserted records.
CSV File will be having data to create a records as well as file name and file path(from local drive).
I have managed to insert a records and upload the given file under Notes & Attachment section of the newly created records. But when I download the uploaded file it will show the error message that file is damaged, which means Im not reading the file properly that resulting in inserting damaged file in Notes & Attachment.
below is my piece of code, can any one help me in reading file path from csv and uploading the corresponding file in Salesforce?
Apex Controller which is used to insert a Attachment file:
for(Integer rowCount = 0 ; rowCount < listOfRows.size() ; rowCount++){ //It will iterate through each row of CSV File
List<String> row = listOfRows[rowCount];
for(Integer docCount = rowCount ; docCount<docsAttachmentList.size() ; docCount++){ //It will iterate through newly created records, in which I have to Insert a file
Documents_Attachments__c doc = docsAttachmentList[docCount];
if(row[0] == doc.COPF_ID__c){
Attachment attacmentRec = new Attachment();
attacmentRec.ParentId = doc.Id;
attacmentRec.Name = row[2]; //row[2] is a file name
attacmentRec.ContentType=contentType;
attacmentRec.Body = Blob.valueOf(row[3]); //row[3] is a file path
attachmentToInsertList.add(attacmentRec);
break;
}
}
}
insert attachmentToInsertList;
VF Page :
<apex:page controller="BulkUploadAttachmentsController">
<apex:form >
<apex:sectionHeader title="Upload CSV File"/>
<apex:pageBlock Title="CSV File Upload Section" >
<apex:inputFile value="{!contentFile}" filename="{!nameFile}" contentType="{!contentType}" accept="csv"/>
Select The Document type : <apex:selectList id="chooseColor" value="{!recordType}" size="1">
<apex:selectOption itemValue="- None -" itemLabel="- None -"/>
<apex:selectOption itemValue="Handover to PM" itemLabel="Handover to PM"/>
<apex:selectOption itemValue="Handover to SS" itemLabel="Handover to SS"/>
</apex:selectList>
<apex:pageBlockButtons location="Bottom" >
<apex:commandButton action="{!BulkUploadAttachmentsController}" value="Upload File" id="theButton" style="width:70px;" />
</apex:pageBlockButtons>
</apex:pageBlock>
</apex:form>