I'm trying to save and display a image for each contact individually. I was able to save the image successfully at respective contact. But, when i refreshed the page the photo i have attached is not displaying. Here is the code:
<apex:page standardController="Contact" extensions="photo_attachmentcls">
<apex:pageBlock >
<apex:form >
<apex:inputFile value="{!attach}" fileName="{!fileName}"></apex:inputFile>
<apex:commandButton value="Load" action="{!loader}" />
<apex:actionSupport event="onchange" />
</apex:form>
<apex:outputPanel id="iidd1">
<img id="theImage" src="/servlet/servlet.FileDownload?file={!dsa}" width="100" height="100" />
</apex:outputPanel>
</apex:pageBlock>
</apex:page>
public class photo_attachmentcls {
public Attachment asd{get;set;}
public string purl{get;set;}
public blob attach{get;set;}
public String fileName{get;set;}
public Id recId{get;set;}
public String dsa {get;set;}
public photo_attachmentcls(ApexPages.StandardController ctrl) {
recId = ApexPages.currentPage().getParameters().get('id');
asd = new Attachment();
}
public void loader()
{
asd.body = attach;
asd.Name = fileName;
asd.ParentId = recId;
insert asd;
system.debug('nnnn'+asd);
dsa = asd.id;
system.debug('ddddd'+dsa);
}
}
Thanks in Advance.
You need to check for the existence of the attachment for that record when the page loads:
public class photo_attachmentcls {
public Attachment asd{get;set;}
public string purl{get;set;}
public blob attach{get;set;}
public String fileName{get;set;}
public Id recId{get;set;}
public String dsa {get;set;}
public photo_attachmentcls(ApexPages.StandardController ctrl) {
recId = ApexPages.currentPage().getParameters().get('id');
// check if the contact already has an attachment:
Contact thisRecord = [select id, (Select Id From NotesAndAttachments) from Contact where Id =: recId];
if(!thisRecord.NotesAndAttachments.isEmpty()){
dsa = thisRecord.NotesAndAttachments[0].Id;
} else{
asd = new Attachment();
}
}
public void loader()
{
asd.body = attach;
asd.Name = fileName;
asd.ParentId = recId;
insert asd;
system.debug('nnnn'+asd);
dsa = asd.id;
system.debug('ddddd'+dsa);
}
}
I'll recommend to choose better variable names as well, but I recognize is a prototype of some sort.