Upload Files In LWC- ๐˜ญ๐˜ช๐˜จ๐˜ฉ๐˜ต๐˜ฏ๐˜ช๐˜ฏ๐˜จ-๐˜ช๐˜ฏ๐˜ฑ๐˜ถ๐˜ต ๐˜ท๐˜ด ๐˜ญ๐˜ช๐˜จ๐˜ฉ๐˜ต๐˜ฏ๐˜ช๐˜ฏ๐˜จ-๐˜ง๐˜ช๐˜ญ๐˜ฆ-๐˜ถ๐˜ฑ๐˜ญ๐˜ฐ๐˜ข๐˜ฅ

ย 

ย 

Hereโ€™s the deal๐Ÿ’ก:

๐˜ญ๐˜ช๐˜จ๐˜ฉ๐˜ต๐˜ฏ๐˜ช๐˜ฏ๐˜จ-๐˜ช๐˜ฏ๐˜ฑ๐˜ถ๐˜ต ๐˜ต๐˜บ๐˜ฑ๐˜ฆ=“๐˜ง๐˜ช๐˜ญ๐˜ฆ”

  • ๐Ÿ‘‰Use this when you want to handle files locally (e.g., reading file contents for processing).
  • ๐Ÿ‘‰Perfect for things like previewing files or parsing data (think CSVs) and do process in JS with this data rather than saving it in backend.
  • ๐Ÿ‘‰An input field for selecting files to upload using an Upload Files button or a drag-and-drop zone. This field accepts files up to 3.5 MB.
  • ๐Ÿ‘‰You will need to custom Apex logic in case you need to save the file and remember about 6mb Heap size limit in apex.
  • ๐Ÿ‘‰To retrieve the list of selected files, use event.target.files in the onchange event handler. Your selected files are returned in a FileList object, each specified as a File object with the size and type attributes.

Below example allows you to upload an image or Zip file.

<template>
    <lightning-input
        type="file"
        label="Attachment"
        accept="image/png, .zip"
        onchange={handleFilesChange}
        multiple
    >
    </lightning-input>
</template>

lightning-input type=“file” handles file selection only. Implement your own file uploading. For example, wire up your component to an Apex controller that handles file uploads. Alternatively, use the lightning-file-upload component for an integrated way to upload files to records.

๐˜ญ๐˜ช๐˜จ๐˜ฉ๐˜ต๐˜ฏ๐˜ช๐˜ฏ๐˜จ-๐˜ง๐˜ช๐˜ญ๐˜ฆ-๐˜ถ๐˜ฑ๐˜ญ๐˜ฐ๐˜ข๐˜ฅ

  • ๐Ÿ‘‰Use this when you need to upload files directly into Salesforce as ContentVersion records.
  • ๐Ÿ‘‰It handles files up to 2GB and comes with a built-in progress bar!
  • ๐Ÿ‘‰Use onuploadfinished event handler to handle post upload logics in js
  • ๐Ÿ‘‰To associate an uploaded file to a record, specify the record-id attribute

Below example creates a file uploader that allows multiple PDF and PNG files to be uploaded.

<template>
    <lightning-file-upload
        label="Upload File"
        name="fileUploader"
        accept={acceptedFormats}
        record-id={myRecordId}
        onuploadfinished={handleUploadFinished}
        multiple
    >
    </lightning-file-upload>
</template>
import { LightningElement, api } from 'lwc';
export default class FileUploadExample extends LightningElement {
    @api
    myRecordId;

    get acceptedFormats() {
        return ['.pdf', '.png'];
    }

    handleUploadFinished(event) {
        // Get the list of uploaded files
        const uploadedFiles = event.detail.files;
        alert('No. of files uploaded : ' + uploadedFiles.length);
    }
}

Do add any value points you can think of down in comments!๐Ÿ”ฆ๐Ÿ”ฆ๐Ÿ”ฆ

Read more

This Content was originally posted in linkedin View Post