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
Emmanuel CoronaEmmanuel Corona 

Attach only pdf or zip files

Greetings!

 

I have my page for upload files but i want to restrict the file type only for PDF or ZIP 

 

i have in code: 

 

<apex:inputFile accept=".zip,.pdf*" value="{!attach.body}" filename="{!attach.name}" required="True"/>

 

But on Iexplorer, Mozilla, Chrome and safari i can upload any type of files.

 

Thank you so much!

Best Answer chosen by Admin (Salesforce Developers) 
Salesforce SolutionsSalesforce Solutions

For the JavaScript, something like this should work:

 

if(!(ext == "pdf" || ext =="zip"))
{
obj.value = null;
window.alert("Only pdf or zip files can be uploaded.");
return false;
}

 

All Answers

Avidev9Avidev9
try accept="application/zip,application/pdf"
Emmanuel CoronaEmmanuel Corona
Hey Hello Avidev! yes i tried that before but without success :(
Emmanuel CoronaEmmanuel Corona
the only browser that works with the first code is Chrome, i don't know why Iexplorer, Firefox or Safari works with that.
Salesforce SolutionsSalesforce Solutions

1. You can use javascript on the client side to block the upload.


Here's an example from http://murthyvvr.blogspot.com/2013/05/apex-input-file-type-validation-using.html

 

<apex:inputFile required="true" value="{!document.body}" filename="{!document.name}" onchange="check(this)" id="filePath"/>


<script type = "text/javascript">
function check(obj) {
var path = obj.value;
var ext = path.substring(path.lastIndexOf('.') + 1);

if(ext !="xlsm")
{
obj.value = null;
window.alert("Please select only xlsm");
return false;
}
}
</script>

 
(Have not tested this, so cannot vouch for it.)

2. In any case, you should check on the server side to make sure the extension is OK.
Assuming you are creating an Attachment object with the file, if the object name is atm, you can do something like:

 

String extension = atm.Name.substringAfterLast('.').toLowerCase();

// if the extension is not OK, then delete the attachment object and set a property that will display
// an error message to the user on the VisualForce page

 



Emmanuel CoronaEmmanuel Corona
Wow! thank you Salesforce Solutions, but is only for one type of file correct? i need for PDF or ZIP only is possible?
Salesforce SolutionsSalesforce Solutions

For the JavaScript, something like this should work:

 

if(!(ext == "pdf" || ext =="zip"))
{
obj.value = null;
window.alert("Only pdf or zip files can be uploaded.");
return false;
}

 

This was selected as the best answer
Emmanuel CoronaEmmanuel Corona
Wow! it works!!!

Thank you Salesforce Solutions