Visualforce Image Uploader

In this post, I am going to explain how to implement visualforce page image uploader which looks similar to the salesforce standard file upload features.

The final look of the Visualforce page looks as shown below. After uploading the image it will be added to the contact Attachments section. It is going to allow the only certain type of image types.


Understanding Controller.

The controller is having the two variables names imagesTypes, notAllowedTypes which are used to support the Images types that are allowed to upload, restrict as shown below.

private Set<String> imagesTypes = new Set<String> {‘image/jpeg’, ‘image/pjpeg’, ‘image/png’, ‘image/x- png’, ‘image/gif’};
private Set<String> notAllowedTypes = new Set<String> {‘application/octet-stream’ , ‘image/bmp’};
The below logic is used to performs the upload logic

public PageReference uploadAction(){
PageReference thePage = new PageReference( ‘/’+ parentId );
thePage.setRedirect( true );
if( this.validate() ){
return ( this.saveCurrentPicture() ) ? thePage : null;
this.newAttach = new Attachment();
return null;
public Boolean saveCurrentPicture(){
Savepoint sp = Database.setSavepoint();
this.newAttach.parentId = this.parentId; = ‘Contact Picture’;
insert this.newAttach;
return true;
catch( Exception e ){
this.error += ERROR_NO_SAVE+'<br/>’;
Database.rollback( sp );
return false;
How to validate the image types?

below piece of logic is used to validate allowed image types that are uploaded.

private Boolean validate(){
Boolean ret = true;
this.error = ”;
if( !imagesTypes.contains( newAttach.ContentType ) ){
this.error += ERROR_IMG_TYPE+'<br/>’;
ret = false;
return ret;
Understanding Visauflorce Page logic.

Most important logic in the visualforce page is validating the image name length. the following javascript logic validates
the Image name length on upload Command Button Click.
function verifyNameLength(){
var textVal = document.getElementsByName(‘uploadImagePage:uploadAttachment:newAttach:inputFile:file’)[0].value;

if( textVal != “” ) {
var browser = navigator.userAgent;
var fileName = textVal;

if( ‘MSIE’ ) > 0 ) {
var index = textVal.lastIndexOf( ‘\\’ );
fileName = textVal.substring( index +1);

if( fileName.length < 70) {
return true;
if( textVal == “” ) {
alert( ‘Please select an image to upload’ );
} else {
alert( ‘The file name must be 70 characters maximum’ );
return false;

The above logic is invoked from the Upload button to throw an error for length more than 70.

<apex:commandButton id=”Accept” action=”{!uploadAction}” value=”Upload” onclick=”return verifyNameLength();”></apex:commandButton>
Complete URL for the GitHub source code