function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
sfadm sfadmsfadm sfadm 

Apex file validation. How to validate the uploaded file is ".csv" or not?

As described in the following article:
​https://developer.salesforce.com/forums/?id=906F0000000BPXxIAO
I make the suggested validation to finind out if the uploaded file is ".csv" or not. Therefore I'm using the suggested try/catch in my controller class 
blob docBlob = doc.body;
string blobString;
try
{
blobString = docBlob.toString();
}
catch(Exception e)
    {
        ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.FATAL,'Please upload a valid CSV document');
        ApexPages.addMessage(myMsg); 
        return ;   
    }

The try/catch is working for specific file formats such as:
".pdf" , ".xlsx", ".docx".

But when I try to upload files with the following file formats:
".log", ".eml", ".cls"
they become successfully uploaded in Salesforce, creating hundreds of records in Salesforce which is totaly wrong and inadmissable.

Please advise how to adjust the try/catch block in order to allow only ".csv" file formats to be uploaded?
 
Best Answer chosen by sfadm sfadm
Raj VakatiRaj Vakati
String fileName = 'foobar.csv';
Set<String> acceptedExtensions = new Set<String> {'.csv','.txt', '.jpg'};

Boolean found = false;
for(String s : acceptedExtensions){
    if(found = fileName.endsWith(s)){ // yes, there's only one "=", I do want assignment here
        break;
    }
}
if(!found){ // after the whole loop it's still false?
    ApexPages.addMessage(...);
}

https://stackoverflow.com/questions/21300048/validate-file-extensions-in-apex