πŸš€ Upload Multiple Files Using Lightning Web Component (LWC) in Salesforce

The lightning-file-upload component offers a simple, built-in solution for users to upload multiple files in Lightning Experience. It supports both drag-and-drop and manual file selection, and allows file type filtering through the accept attribute.

Key Features:

  • Drag-and-drop support for intuitive uploads.
  • File type restriction using the accept attribute.
  • Multiple file upload capability.
  • Automatic association of uploaded files to a specific record using the record-id attribute (required).
  • Native styling based on the Salesforce Lightning Design System (SLDS).

Notes:

  • Uploaded files are saved under Files Home (Owned by Me filter) and are also accessible via the Attachments related list on the associated record’s detail page.
  • While all Salesforce-supported file formats are allowed by default, you can limit uploads to specific formats using the accept attribute.
 <lightning-input
                type="file"
                accept={acceptedTypesString}
                onchange={handleFileUpload}
                class="slds-m-bottom_xx-small validate-input"
                required={required}
                label={fieldlabel}
                multiple
               >
 </lightning-input>
handleFileUpload(event) {
        const files = event.detail.files;
        this.error = null;
        this.validationError = '';
        this.hasUserInteracted = true;

        if (files.length + this.instanceFiles.length > this.maxFiles) {
            this.error = `You can upload maximum ${this.maxFiles} files in this section.`;
            return;
        }

        for (const file of files) {
            const fileExtension = '.' + file.name.split('.').pop().toLowerCase();

            if (!this.acceptedTypes.includes(fileExtension)) {
                this.error = `File type ${fileExtension} is not allowed.`;
                return;
            }

            if (file.size > this.maxFileSize * 1024 * 1024) {
                this.error = `File ${file.name} exceeds maximum size of ${this.maxFileSize}MB.`;
                return;
            }
        }

        this.processFiles(files);
    }

    processFiles(files) {
        const fileReaders = Array.from(files).map(file => {
            return new Promise((resolve) => {
                const reader = new FileReader();
                reader.onload = () => {
                    resolve({
                        filename: file.name,
                        base64Data: reader.result.split(',')[1],
                        description: this.description // Include description in the file data
                    });
                };
                reader.onerror = () => {
                    this.error = 'Error reading file';
                    resolve(null);
                };
                reader.readAsDataURL(file);
            });
        });

        Promise.all(fileReaders)
            .then(fileDataArray => {
                const validFiles = fileDataArray.filter(file => file !== null);
                if (validFiles.length === 0) {
                    throw new Error('No valid files to upload');
                }
                return uploadFiles({
                    fileData: JSON.stringify(validFiles),
                    caseId: this.caseId,
                    description: this.description
                });
            })
            .then(apexResult => {
                if (apexResult?.length > 0) {
                    const newFiles = apexResult.map(file => ({
                        documentId: file.ContentDocumentId,
                        name: file.Title,
                        description: file.Description || this.description, // Use file.Description if available
                        size: (file.ContentSize / 1024).toFixed(2),
                        url: `/sfc/servlet.shepherd/document/download/${file.ContentDocumentId}`,
                        elementname: this.elementname
                    }));

                    this.instanceFiles = [...this.instanceFiles, ...newFiles];
              
                } else {
                    throw new Error('No files were uploaded successfully');
                }
            })
            .catch(error => {
                console.error('Upload error:', error);
                this.error = error.body?.message || error.message || 'Error uploading files';
            });
    }

πŸ“‚ File Upload Limits in Salesforce

When using file uploads in Lightning Web Components, it’s important to understand Salesforce’s default and configurable limits:

πŸ”’ File Count Limits

  • Default limit: Up to 10 files can be uploaded simultaneously.
  • Configurable range: Your Salesforce admin can set the limit between 1 and 25 files per upload session.

πŸ“ File Size Limits

  • Maximum file size: Up to 2 GB per file.
  • In Communities:
    • File size and type restrictions follow community file moderation settings.
    • Limits may vary depending on how your Salesforce Community is configured.

πŸ”’ Guest User Restrictions

  • By default, guest users cannot upload files.
  • You can enable this capability by updating your org’s guest user file upload settings in Setup.