Skip to content

Instantly share code, notes, and snippets.

@sfcure
Last active December 1, 2017 08:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sfcure/4b2a528df045fb2e5165e8161a22705b to your computer and use it in GitHub Desktop.
Save sfcure/4b2a528df045fb2e5165e8161a22705b to your computer and use it in GitHub Desktop.
Upload Attachment through Force.com sites
<apex:page controller="UploadAttachmentController">
<script type="text/javascript">
function alertFilesize(){
if(window.ActiveXObject){
var fso = new ActiveXObject("Scripting.FileSystemObject");
var filepath = document.getElementById('j_id0:j_id2:fileInput').value;
var thefile = fso.getFile(filepath);
var sizeinbytes = thefile.size;
}else{
var sizeinbytes = document.getElementById('j_id0:j_id2:fileInput').files[0].size;
}
var fSExt = new Array('Bytes', 'KB', 'MB', 'GB');
fSize = sizeinbytes; i=0;while(fSize>900){fSize/=1024;i++;}
alert(' File Size should be less than 10 MB. Your current file size is ' + (Math.round(fSize*100)/100)+' '+fSExt[i]);
}
</script>
<apex:form>
<apex:pageMessages id="msg"></apex:pageMessages>
<div style="display:block; width: 10%; float:left; margin-bottom: 10px;">
Choose a file
</div>
<div style="display:block; width: 90%; float:left; margin-bottom: 10px;">
<apex:inputFile id="fileInput" onchange="alertFilesize();" value="{!attBody}" fileName="{!fileName}" fileSize="{!fileSize}" contentType="{!contentType}"></apex:inputFile>
</div>
<div style="display:block; width: 10%; float:left; margin-bottom: 10px;">
</div>
<div style="display:block; width: 90%; float:left; margin-bottom: 10px;">
<apex:commandButton action="{!uploadFile}" value="Upload File"/>
</div>
</apex:form>
</apex:page>
public class UploadAttachmentController {
public Blob attBody { get; set; }
public String fileName { get; set; }
public Integer fileSize { get; set; }
public String contentType { get; set; }
private Id parentRecordId;
public UploadAttachmentController(){
parentRecordId = ApexPages.currentPage().getParameters().get('id');
}
public PageReference uploadFile() {
if( attBody != null ) {
Attachment att = new Attachment( Body = attBody,
Name = fileName,
ParentId = parentRecordId,
ContentType = contentType );
try {
insert att;
ApexPages.addMessage(new ApexPages.Message( ApexPages.severity.CONFIRM, 'File uploaded successfully.') );
} catch ( Exception e ) {
ApexPages.addMessage(new ApexPages.Message( ApexPages.severity.ERROR, 'File upload failed due to "' + e.getMessage() + '".') );
}
attBody = null;
fileName = '';
}
else {
ApexPages.addMessage(new ApexPages.Message( ApexPages.severity.ERROR, 'Please choose a file.') );
}
PageReference pg = Page.UploadAttachment;
pg.setRedirect( false );
return pg;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment