Enhance User Experience with Image Upload & Preview Using LWC.

Enhance User Experience with Image Upload & Preview Using LWC.

Hello friends,

Are you looking to improve your users' experience when they upload images? Do you want to:

  1. Allow users to preview uploaded images before processing?
  2. Give users the ability to remove uploaded images from the list?

Look no further! My Lightning Web Components (LWC) can help you achieve this seamless user experience. This LWC solution lets users upload images, preview them, and manage their uploads with ease.

Note: This component is designed specifically for image uploads (.jpg, .png, .jpeg, .webp , .pjpeg) and does not support other formats like PDF, XLSX, PPT, etc.


HTML:

<template>
    <!-- Kiruba Sankar M / 21/07/2024 -->
    <lightning-card icon-name="utility:photo" title="Upload & Preview File Before Saving File To Salesforce">
        <div class="row">
            <div class="custom-box">
                <lightning-input
                    type="file"
                    multiple
                    onchange={openfileUpload}
                    accept={acceptedFormats}
                ></lightning-input>
            </div>
        </div>
        <!-- Uploaded Image -->
        <div class="badge-container">
            <template for:each={fileDataList} for:item="file">
                <div key={file.id} class="badge">
                    <p>{file.filename}</p>
                    <lightning-button-icon
                        icon-name="utility:preview"
                        alternative-text="Preview"
                        variant="brand"
                        onclick={handlePreviewFile}
                        data-id={file.id}
                        class="slds-m-left_x-small"
                    ></lightning-button-icon>
                    <lightning-button-icon
                        icon-name="utility:close"
                        alternative-text="Remove"
                        onclick={handleRemove}
                        data-id={file.id}
                        class="slds-m-left_x-small"
                        variant="error"
                        size="medium"
                    ></lightning-button-icon>
                </div>
            </template>
        </div>

        <!-- File Preview -->
        <div class="file-preview-container" lwc:if={showFilePreview}>
            <img src={imageSrc} alt="File Preview" />
        </div>

        <div class="buttons">
            <lightning-button label="Clear Preview" onclick={onClearPreview} variant="brand"> </lightning-button>
            <lightning-button label="Submit" onclick={onSubmitRecentPhoto} variant="success"> </lightning-button>
        </div>
    </lightning-card>
</template>        


JS:

import { LightningElement, track } from "lwc";
import { ShowToastEvent } from "lightning/platformShowToastEvent";

export default class UploadRecentPassportImage extends LightningElement {
    openModal = true;
    showFilePreview;
    imageSrc;
    acceptedFormats = [".jpg", ".png", ".jpeg", ".pjpeg", ".webp"];
    @track fileDataList = [];

    openfileUpload(event) {
        const files = event.target.files;
        for (let i = 0; i < files.length; i++) {
            const file = files[i];
            const reader = new FileReader();
            reader.onload = () => {
                const base64 = reader.result.split(",")[1];
                const fileData = {
                    id: this.fileDataList.length + 1,
                    filename: file.name,
                    base64: base64,
                    recordId: this.recordId
                };
                this.fileDataList = [...this.fileDataList, fileData];
                console.log("File name " + JSON.stringify(file.name));
            };
            reader.readAsDataURL(file);
        }
    }

    handleRemove(event) {
        this.showFilePreview = false;
        const fileId = event.target.dataset.id;
        this.fileDataList = this.fileDataList.filter((file) => file.id !== parseInt(fileId));
    }

    handlePreviewFile(event) {
        const fileId = event.target.dataset.id;
        console.log("fileId", fileId);

        const file = this.fileDataList.find((file) => file.id === parseInt(fileId));
        if (file) {
            const fileName = file.filename;
            const extensionType = fileName.split(".")[fileName.split(".").length - 1];
            const base64 = file.base64;
            this.imageSrc = `data:image/${extensionType};base64,${base64}`;
            this.showFilePreview = true;
        }
    }

    onClearPreview() {
        this.showFilePreview = false;
    }
    onSubmitRecentPhoto() {
        //Handle the files which are stored in this.fileDataList for further processing.
    }

    handleModalClose() {
        this.openModal = false;
    }

    showToast(title, message, variant) {
        const evt = new ShowToastEvent({
            title,
            message,
            variant
        });
        this.dispatchEvent(evt);
    }
}        
CSS:

.file-preview-container {
    padding: 1rem;
    margin-top: 1rem;
    border: 2px solid black;
    text-align: center;
}
.file-preview-container img {
    width: 500px;
}
.buttons,
.row {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 5px;
    flex-wrap: wrap;
    margin: 1rem;
}

.badge-container {
    margin-top: 1rem;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
}
.badge {
    display: flex;
    justify-content: center;
    align-items: center;
    border-top-right-radius: 10px;
    border-top-left-radius: 10px;
    border-bottom-left-radius: 10px;
    border-bottom-right-radius: 10px;
    background-color: #f2f2f2;
    border: 2px solid black;
    padding: 10px;
    font-weight: 700;
}        

Thank you for reading, and happy coding!

Sujatha Ramadoss

Certified Salesforce Administrator / Developer Salesforce Career Development Program

7 个月

Thanks Kiruba.

要查看或添加评论,请登录

Kiruba Sankar的更多文章

社区洞察

其他会员也浏览了