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
Del_SantosDel_Santos 

Visualforce Validation to prevent user from attaching a non-jpeg file?

Hi Guys,

 

Below is the code for attaching a file in a record. I want to create a validation rule so that user can only upload jpeg files. Is there a way to do this? please help.

 

Thanks,

Del

 

 

 

public with sharing class AttachmentUploadController {
 
  public Attachment attachment {
  get {
      if (attachment == null)
        attachment = new Attachment();
      return attachment;
    }
  set;
  }
 
  public PageReference upload() {
 
    attachment.OwnerId = UserInfo.getUserId();
    attachment.ParentId = '001W0000005v6Ih'; // the record the file is attached to
    attachment.IsPrivate = true;
 
    try {
      insert attachment;
    } catch (DMLException e) {
      ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error uploading attachment'));
      return null;
    } finally {
      attachment = new Attachment(); 
    }
 
    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Attachment uploaded successfully'));
    return null;
  }
 
}

Best Answer chosen by Admin (Salesforce Developers) 
AditiSFDCAditiSFDC

Try this piece of code : 

 

Page

 

<apex:page controller="testPageController">

<apex:sectionHeader title="Visualforce Example" subtitle="Attachment Upload Example"/>

<apex:form enctype="multipart/form-data">
<apex:pageMessages />
<apex:pageBlock title="Upload a Attachment">

<apex:pageBlockButtons >
<apex:commandButton action="{!upload}" value="Save"/>
</apex:pageBlockButtons>

<apex:pageBlockSection showHeader="false" columns="1" id="block1">

<apex:pageBlockSectionItem >
<apex:outputLabel value="File" for="file"/>
<apex:inputFile value="{!attachment.body}" filename="{!attachment.name}" id="file"/>
</apex:pageBlockSectionItem>

<apex:pageBlockSectionItem >
<apex:outputLabel value="Description" for="description"/>
<apex:inputTextarea value="{!attachment.description}" id="description"/>
</apex:pageBlockSectionItem>

</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>

 

Controller

 

public class testPageController {

public Attachment attachment {
get {
if (attachment == null)
attachment = new Attachment();
return attachment;
}
set;
}

public PageReference upload() {

attachment.OwnerId = UserInfo.getUserId();
attachment.ParentId = '001d000000Cto4Z'; // the record the file is attached to
attachment.IsPrivate = true;

try
{
if(attachment.name.toUpperCase().contains('JPG') || attachment.name.toUpperCase().contains('JPEG') )
{
system.debug('Image is of type jpg or jpeg');
insert attachment;
}
else
{
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Please upload a jpg/jpeg file only'));
return null;
}
}
catch (DMLException e)
{
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error uploading attachment'));
return null;
}
finally
{
attachment = new Attachment();
}


ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Attachment uploaded successfully'));
return null;
}
}

All Answers

Navatar_DbSupNavatar_DbSup

Hi,

You can validate an attachment in controller through the ContentType field.

Try the below code snippet as reference:

public with sharing class AttachmentUploadController {

 

  public Attachment attachment {

  get {

      if (attachment == null)

        attachment = new Attachment();

      return attachment;

    }

  set;

  }

 

  public PageReference upload() {

 

    attachment.OwnerId = UserInfo.getUserId();

    attachment.ParentId = '001W0000005v6Ih'; // the record the file is attached to

    attachment.IsPrivate = true;

 

    try

                {

               

                                if(attachment.ContentType!='jpg' || attachment.ContentType!='jpeg')

                                {

                                                ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Please updaload a jpgfiled'));

                                                return null;

                                }

                                insert attachment;

    }

                catch (DMLException e)

                {

      ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error uploading attachment'));

      return null;

    }

                finally

                {

      attachment = new Attachment();

    }

 

    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Attachment uploaded successfully'));

    return null;

  }

 

}

 

Did this answer your question? If not, let me know what didn't work, or if so, please mark it solved. 

Del_SantosDel_Santos

Hi Ankit,

 

Thanks. I tried the code but the validation is also blocking a jpg and jpeg upload. :(

rohitsfdcrohitsfdc

Try changing following line

    if(attachment.ContentType!='jpg' || attachment.ContentType!='jpeg')

 to

    if(attachment.ContentType!='image/jpg' || attachment.ContentType!='image/jpeg')

 

Del_SantosDel_Santos

Hi Rohit,

 

Thanks for the suggestion! But it is still not working in my case.

 

 

Regards,

Del

AditiSFDCAditiSFDC

Try using this, as ContentType field is of String datatype.

 

if(attachment.ContentType.contains('jpg') || attachment.ContentType.contains('jpeg') )
{

insert attachment;
} else {
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Please updaload a jpgfiled'));
return null;
}

Del_SantosDel_Santos

Hi Aditi,

 

I am encountering below error.

 

 

Attempt to de-reference a null object

Error is in expression '{!upload}' in component <apex:page> in page attachmentuploadcontroller

 

 

An unexpected error has occurred. Your development organization has been notified.

AditiSFDCAditiSFDC
Can you please post your Apex page code also so that I can try to execute the code in my own developer org.
Del_SantosDel_Santos

Hi Aditi,

 

Thanks for the interest. Here's my contoller and page.

 

 

 

class:

 

public with sharing class AttachmentUploadController {
 
  public Attachment attachment {
  get {
      if (attachment == null)
        attachment = new Attachment();
      return attachment;
    }
  set;
  }
 
  public PageReference upload() {
 
    attachment.OwnerId = UserInfo.getUserId();
    attachment.ParentId = '001W0000005v6Ih'; // the record the file is attached to
    attachment.IsPrivate = true;
 
    try
                {
                            /*
                                if(attachment.ContentType.contains('jpg') || attachment.ContentType.contains('jpeg') )
                                {
                                insert attachment;
                                }
                                else
                                {
                                ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Please updaload a jpgfiled'));
                                return null;
                                }
                            */
              
                                if(attachment.ContentType!='jpeg' || attachment.ContentType!='jpg')
                                {
                                                ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Only jpeg file is allowed'));
                                                return null;
                                }
                                insert attachment;
    }
                catch (DMLException e)
                {
      ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error uploading attachment'));
      return null;
    }
                finally
                {
      attachment = new Attachment();
    }
 
    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Attachment uploaded successfully'));
    return null;
  }
 
}

 

 

 

 

Here's my page:

 

<apex:page controller="AttachmentUploadController">

<apex:sectionHeader title="Visualforce Example" subtitle="Attachment Upload Example"/>
 
  <apex:form enctype="multipart/form-data">
    <apex:pageMessages />
    <apex:pageBlock title="Upload a Attachment">
 
      <apex:pageBlockButtons >
        <apex:commandButton action="{!upload}" value="Save"/>
      </apex:pageBlockButtons>
 
      <apex:pageBlockSection showHeader="false" columns="1" id="block1">

         <apex:pageBlockSectionItem >
          <apex:outputLabel value="File" for="file"/>
          <apex:inputFile value="{!attachment.body}" filename="{!attachment.name}" id="file"/>
        </apex:pageBlockSectionItem>

        <apex:pageBlockSectionItem >
          <apex:outputLabel value="File Name" for="fileName"/>
          <apex:inputText value="{!attachment.name}" id="fileName"/>
        </apex:pageBlockSectionItem>
 
        
        <apex:pageBlockSectionItem >
          <apex:outputLabel value="Description" for="description"/>
          <apex:inputTextarea value="{!attachment.description}" id="description"/>
        </apex:pageBlockSectionItem>
 
      </apex:pageBlockSection>
 
    </apex:pageBlock>
  
  </apex:form>
</apex:page>

Del_SantosDel_Santos

Hi,

 

FYI. I am running the page through Force.Sites

AditiSFDCAditiSFDC

Try this piece of code : 

 

Page

 

<apex:page controller="testPageController">

<apex:sectionHeader title="Visualforce Example" subtitle="Attachment Upload Example"/>

<apex:form enctype="multipart/form-data">
<apex:pageMessages />
<apex:pageBlock title="Upload a Attachment">

<apex:pageBlockButtons >
<apex:commandButton action="{!upload}" value="Save"/>
</apex:pageBlockButtons>

<apex:pageBlockSection showHeader="false" columns="1" id="block1">

<apex:pageBlockSectionItem >
<apex:outputLabel value="File" for="file"/>
<apex:inputFile value="{!attachment.body}" filename="{!attachment.name}" id="file"/>
</apex:pageBlockSectionItem>

<apex:pageBlockSectionItem >
<apex:outputLabel value="Description" for="description"/>
<apex:inputTextarea value="{!attachment.description}" id="description"/>
</apex:pageBlockSectionItem>

</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>

 

Controller

 

public class testPageController {

public Attachment attachment {
get {
if (attachment == null)
attachment = new Attachment();
return attachment;
}
set;
}

public PageReference upload() {

attachment.OwnerId = UserInfo.getUserId();
attachment.ParentId = '001d000000Cto4Z'; // the record the file is attached to
attachment.IsPrivate = true;

try
{
if(attachment.name.toUpperCase().contains('JPG') || attachment.name.toUpperCase().contains('JPEG') )
{
system.debug('Image is of type jpg or jpeg');
insert attachment;
}
else
{
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Please upload a jpg/jpeg file only'));
return null;
}
}
catch (DMLException e)
{
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error uploading attachment'));
return null;
}
finally
{
attachment = new Attachment();
}


ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Attachment uploaded successfully'));
return null;
}
}

This was selected as the best answer
Del_SantosDel_Santos

This is great! Thanks Aditi! I appreciate your effort.

 

Regards,

Del