82 / 100 SEO Score

Step-by-Step Guide to Uploading Multiple Files in Salesforce Screen Flows

Step-by-Step Guide to Uploading Multiple Files in Salesforce Screen Flows

Introduction: Guide to Uploading Multiple Files in Salesforce Screen Flows

Salesforce Screen Flows provide a powerful way to create dynamic, user-friendly interfaces for data entry and automation. One common requirement is allowing users to upload multiple files within a flow, such as attachments, contracts, or supporting documents. While Salesforce supports file uploads via Lightning Web Components (LWC) and Apex, integrating this functionality into a Screen Flow requires careful configuration.

In this comprehensive guide, we’ll walk through the step-by-step process of enabling multiple file uploads in a Salesforce Screen Flow.

1. Understanding File Upload Limitations in Flows

Salesforce Screen Flows do not natively support multiple file uploads. The standard File Upload screen component only allows a single file per upload, which is insufficient for many business use cases.

Possible Solutions:

For this guide, we’ll focus on building a custom LWC and integrating it into a flow.

2. Setting Up a Custom Lightning Web Component (LWC)

To enable multi-file uploads, we’ll create an LWC that:

Step 1: Create the LWC Structure

1. Open VS Code with Salesforce Extensions.

2. Run SFDX: Create Lightning Web Component (multiFileUploader).

3. Define the following files:

    Step 2: HTML Template (multiFileUploader.html)

    <template>
        <lightning-card title="Upload Multiple Files">
            <div class="slds-p-around_medium">
                <lightning-input 
                    type="file" 
                    label="Upload Files" 
                    multiple 
                    onchange={handleFileChange}>
                </lightning-input>
                <div if:true={filesToUpload}>
                    <p>Selected Files: {filesToUpload.length}</p>
                    <ul>
                        <template for:each={filesToUpload} for:item="file">
                            <li key={file.name}>{file.name}</li>
                        </template>
                    </ul>
                    <lightning-button 
                        label="Upload Files" 
                        variant="brand" 
                        onclick={handleUpload}>
                    </lightning-button>
                </div>
            </div>
        </lightning-card>
    </template>

    Step 3: JavaScript Controller (multiFileUploader.js)

    import { LightningElement, api } from 'lwc';
    import { FlowAttributeChangeEvent } from 'lightning/flowSupport';
    
    export default class MultiFileUploader extends LightningElement {
        @api filesData = []; // Expose to Flow
        filesToUpload = [];
    
        handleFileChange(event) {
            this.filesToUpload = Array.from(event.target.files);
        }
    
        handleUpload() {
            if (this.filesToUpload.length === 0) return;
    
            const fileReaders = [];
            this.filesToUpload.forEach(file => {
                const reader = new FileReader();
                reader.onload = (e) => {
                    const fileContent = e.target.result.split(',')[1]; // Extract base64 data
                    this.filesData.push({
                        fileName: file.name,
                        fileContent: fileContent,
                        fileType: file.type
                    });
                    
                    // Notify Flow of changes
                    this.dispatchEvent(new FlowAttributeChangeEvent('filesData', this.filesData));
                };
                reader.readAsDataURL(file);
            });
        }
    }

    Step 4: Configuration (multiFileUploader.js-meta.xml)

    <?xml version="1.0" encoding="UTF-8"?>
    <LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
        <apiVersion>56.0</apiVersion>
        <isExposed>true</isExposed>
        <targets>
            <target>lightning__FlowScreen</target>
        </targets>
        <targetConfigs>
            <targetConfig targets="lightning__FlowScreen">
                <property name="filesData" type="Object" label="Files Data" description="Stores uploaded file details." />
            </targetConfig>
        </targetConfigs>
    </LightningComponentBundle>

    3. Integrating the LWC into a Screen Flow

    Now that the LWC is ready, we’ll embed it in a flow.

    Step 1: Create a New Screen Flow

    1. Navigate to Setup → Flows → New Flow (Screen Flow).
    2. Add a screen element.
    3. Drag the multiFileUploader LWC into the screen.
    4. Map filesData to a Flow variable (e.g., fileCollection of type Text collection).

    Step 2: Process Uploaded Files with Apex

    Since Flows can’t directly save files, we’ll use an Apex Action to handle storage.

    Apex Class (FileUploaderController.cls)

    public with sharing class FileUploaderController {
        @InvocableMethod(label='Save Files to Record')
        public static List<String> saveFiles(List<FileUploadRequest> requests) {
            List<String> results = new List<String>();
            List<ContentVersion> filesToInsert = new List<ContentVersion>();
    
            for (FileUploadRequest req : requests) {
                ContentVersion cv = new ContentVersion(
                    VersionData = EncodingUtil.base64Decode(req.fileContent),
                    Title = req.fileName,
                    PathOnClient = req.fileName,
                    FirstPublishLocationId = req.recordId // Link to a record
                );
                filesToInsert.add(cv);
            }
    
            insert filesToInsert;
            results.add('Files uploaded successfully');
            return results;
        }
    
        public class FileUploadRequest {
            @InvocableVariable(label='Record ID' required=true)
            public Id recordId;
            
            @InvocableVariable(label='File Name' required=true)
            public String fileName;
            
            @InvocableVariable(label='File Content (Base64)' required=true)
            public String fileContent;
        }
    }

    Adding the Apex Action to the Flow

    1. Add an Apex Action after the Screen.

    2. Select FileUploaderController.saveFiles.

    3. Pass fileCollection from the LWC to the Apex method.

      4. Handling File Storage (Attachments vs. Files)

      Salesforce supports two file storage models:

      Option 1: ContentVersion (Files)

      Option 2: Attachment (Classic)

      Attachment att = new Attachment(
          ParentId = recordId,
          Name = fileName,
          Body = EncodingUtil.base64Decode(fileContent)
      );
      insert att;
      5. Error Handling and Best Practices

      Common Issues & Fixes

      Best Practices

      ✔ Use Progress Indicators – Show upload status in the LWC.
      ✔ Validate Files Before Upload – Check size, type, and extensions.
      ✔ Error Logging – Capture failures in a custom object.
      ✔ Test in Sandbox First – Avoid data corruption in production.

      My Takeaway: 

      Uploading multiple files in Salesforce Screen Flows enhances user interaction and streamlines data collection within business processes. By leveraging Flow Screen components like the File Upload element and proper configuration of related records, admins and developers can create efficient, user-friendly experiences. This low-code solution not only improves file management but also saves time and reduces errors. Mastering this functionality is a valuable skill for any Salesforce professional looking to optimize automation and drive seamless digital engagement in their org.

      Contact Us
      Loading
      Your message has been sent. Thank you!
      © Copyright iTechCloud Solution 2024. All Rights Reserved.