File Upload with Preview in LWC & Apex


Enabling users to upload files and instantly preview them is a powerful way to improve UX in Salesforce Lightning apps. In this blog, we will learn about the need we might want for this feature, our org and user stories before we start, steps to build it step by step (with full code), actual use cases of using this approach and the way to extend it beyond images. Let’s move forward and check on this blog to learn about File Upload with Preview in LWC & Apex.

Actual User Requirements

Before writing a single line of code, gather below core requirements as per any business:

  1. Record Context:
    Users must be on a specific record (e.g. Account, Case) so uploaded files attach to that record.
  2. Instant Preview:
    For images especially, users expect to see what they have chosen before moving forward to “Upload” in Salesforce.
  3. File Size & Type Limits:
    We need to decide the maximum size like 2 MB and acceptable file types like PNG, JPG.
  4. Security & Permissions:
    Running users need to create rights on ContentVersion and ContentDocumentLink.
  5. Graceful Feedback
    Disable the Upload button until a file is selected, show “Uploading…,” and handle errors cleanly or as per business requirement we can add any messages.

With these in hand, our dev plan becomes straightforward: a small Apex controller to save the file and a Lightning Web Component (LWC) for the UI.

Prerequisites

  1. API Version ≥ 50.0
    (The example uses 64.0 in metadata, but any modern org will do.)
    User Permissions
    Ensure profiles or permission sets grant:
    • Create on ContentVersion
    • Create on ContentDocumentLink
  2. Record Page
    We will deploy the LWC to a Record Page so that @api recordId is populated automatically.

Below are the steps for programs that we need to write as part of implementations:

Step 1: Apex Controller

Create a simple, @AuraEnabled Apex method that:

  1. Decodes the Base64 file data from the client
  2. Inserts a ContentVersion
  3. Finds the resulting ContentDocumentId
  4. Links it to the parent record via ContentDocumentLink

Why ContentVersion + ContentDocumentLink?

  • ContentVersion holds the file itself.
  • ContentDocumentLink attaches it to any record.

Step 2: LWC Component

This LWC handles file selection, preview generation, and the upload call.

Markup (fileUpload.html)