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

ย
If youโve ever handled file uploads in Salesforce LWCs, youโve probably wondered when to use lightning-input with type=“file” versus lightning-file-upload๐.
ย
Hereโs the deal๐ก:
Lightning Input ๐
๐ญ๐ช๐จ๐ฉ๐ต๐ฏ๐ช๐ฏ๐จ-๐ช๐ฏ๐ฑ๐ถ๐ต ๐ต๐บ๐ฑ๐ฆ=“๐ง๐ช๐ญ๐ฆ”
- ๐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.
Lightning File Upload๐
๐ญ๐ช๐จ๐ฉ๐ต๐ฏ๐ช๐ฏ๐จ-๐ง๐ช๐ญ๐ฆ-๐ถ๐ฑ๐ญ๐ฐ๐ข๐ฅ
- ๐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