The <apex:inputFile>
component is used to create a file upload field on Visualforce pages, enabling users to upload files from their local system to Salesforce.
Why Use <apex:inputFile>
?
- Allows users to upload files to Salesforce via Visualforce pages.
- Supports file types like images, documents, and other media.
- Useful for scenarios like profile picture uploads, document submissions, or file storage.
Basic Syntax
xmlCopyEdit<apex:inputFile value="{!fileVariable}" label="Upload a File"/>
value
: Binds the uploaded file to an Apex variable (usually aBlob
orAttachment
type).label
: Provides a label for the file input field.
Example: File Upload for Profile Picture
xmlCopyEdit<apex:page controller="FileUploadController">
<apex:form>
<apex:inputFile value="{!userFile}" label="Upload your Profile Picture"/>
<apex:commandButton value="Upload" action="{!uploadFile}"/>
</apex:form>
</apex:page>
Apex Controller:
apexCopyEditpublic class FileUploadController {
public Blob userFile { get; set; }
public void uploadFile() {
// Logic to save file (e.g., as an attachment or document)
System.debug('File Uploaded: ' + userFile);
}
}
Key Attributes
value
: Binds the uploaded file to an Apex variable (typically aBlob
).label
: A descriptive label displayed next to the file upload field.required
: Makes the file upload mandatory for form submission.accept
: Specifies the types of files that can be uploaded (e.g.,.jpg, .png, .pdf
).
Use Cases
- Profile Picture Upload: Let users upload their profile images or avatars.
- Document Submission: Allow users to upload resumes, cover letters, or other documents.
- File Storage: Enable users to upload files for storage or sharing within Salesforce.