File Upload Controller:
public with sharing class FileUploadController { public Document document { get { if (document == null) document = new Document(); return document; } set; } public PageReference upload() { document.AuthorId = UserInfo.getUserId();//Current User Id document.FolderId = UserInfo.getUserId();//Add Folder Id try { insert document; } catch (DMLException e) { ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error uploading file')); return null; } finally { document.body = null;//Clear the View State document = new Document(); } ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Document uploaded successfully')); return null; } }
File Upload Visualforce Page:
<apex:page controller="FileUploadController"> <apex:sectionHeader title="File Upload" subtitle="File Upload Example"/> <apex:form enctype="multipart/form-data"> <apex:pageMessages /> <apex:pageBlock title="Upload a File"> <apex:pageBlockButtons > <apex:commandButton action="{!upload}" value="Save"/> </apex:pageBlockButtons> <apex:pageBlockSection showHeader="false" columns="2"> <apex:pageBlockSectionItem > <apex:outputLabel value="File Name" for="fileName"/> <apex:inputText value="{!document.name}" id="fileName"/> </apex:pageBlockSectionItem> <apex:pageBlockSectionItem > <apex:outputLabel value="File" for="file"/> <apex:inputFile value="{!document.body}" filename="{!document.name}" id="file"/> </apex:pageBlockSectionItem> <apex:pageBlockSectionItem > <apex:outputLabel value="Description" for="description"/> <apex:inputTextarea value="{!document.description}" id="description"/> </apex:pageBlockSectionItem> <apex:pageBlockSectionItem > <apex:outputLabel value="Keywords" for="keywords"/> <apex:inputText value="{!document.keywords}" id="keywords"/> </apex:pageBlockSectionItem> </apex:pageBlockSection> </apex:pageBlock> </apex:form> </apex:page>