Restrict file uploads to only JPG, JPEG, and PNG file types
How This Works
Users select a file through a regular input type="file".
The file type is checked before upload.
If invalid, an error toast appears, and the file selection is reset.
If valid, the hidden is triggered programmatically.
The file gets uploaded only if it's a valid image (JPG, JPEG, PNG).
Benefits of This Approach
✔ Prevents wrong file uploads before reaching Salesforce
✔ Works within the limits of lightning-file-upload
✔ Better user experience with inline validation
Users select a file through a regular input type="file".
The file type is checked before upload.
If invalid, an error toast appears, and the file selection is reset.
If valid, the hidden
The file gets uploaded only if it's a valid image (JPG, JPEG, PNG).
Benefits of This Approach
✔ Prevents wrong file uploads before reaching Salesforce
✔ Works within the limits of lightning-file-upload
✔ Better user experience with inline validation
<script>
<script>
import { LightningElement, api, wire, track } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { getRelatedFiles } from 'lightning/uiRelatedListApi';
import { createRecord } from 'lightning/uiRecordApi';
import CONTENT_DOCUMENT_LINK_OBJECT from '@salesforce/schema/ContentDocumentLink';
import LINKED_ENTITY_ID_FIELD from '@salesforce/schema/ContentDocumentLink.LinkedEntityId';
import CONTENT_DOCUMENT_ID_FIELD from '@salesforce/schema/ContentDocumentLink.ContentDocumentId';
export default class UploadOrSelectFile extends LightningElement {
@api recordId;
@track files = [];
selectedFile;
acceptedFormats = ['.jpg', '.jpeg', '.png']; // Allowed file formats
@wire(getRelatedFiles, { recordId: '$recordId' })
wiredFiles({ error, data }) {
if (data) {
this.files = data.map(file => ({
label: file.Title,
value: file.ContentDocumentId
}));
} else if (error) {
console.error('Error fetching files:', error);
}
}
handleFileSelection(event) {
const selectedFileId = event.target.value;
this.linkFileToRecord(selectedFileId);
}
handleFileChange(event) {
this.selectedFile = event.target.files[0];
if (!this.isValidFileType(this.selectedFile.name)) {
this.showToast('Error', `Invalid file type: ${this.selectedFile.name}. Only JPG, JPEG, and PNG are allowed.`, 'error');
this.selectedFile = null;
event.target.value = ''; // Reset file input
return;
}
// If valid, trigger hidden file upload
this.triggerFileUpload();
}
triggerFileUpload() {
this.template.querySelector('lightning-file-upload').click();
}
handleUploadFinished(event) {
const uploadedFiles = event.detail.files;
this.showToast('Success', `${uploadedFiles.length} file(s) uploaded successfully.`, 'success');
}
isValidFileType(fileName) {
const fileExtension = fileName.slice(fileName.lastIndexOf('.')).toLowerCase();
return this.acceptedFormats.includes(fileExtension);
}
linkFileToRecord(fileId) {
const fields = {};
fields[LINKED_ENTITY_ID_FIELD.fieldApiName] = this.recordId;
fields[CONTENT_DOCUMENT_ID_FIELD.fieldApiName] = fileId;
const recordInput = { apiName: CONTENT_DOCUMENT_LINK_OBJECT.objectApiName, fields };
createRecord(recordInput)
.then(() => {
this.showToast('Success', 'File linked successfully.', 'success');
})
.catch(error => {
this.showToast('Error', 'Failed to link file.', 'error');
console.error('Error linking file:', error);
});
}
showToast(title, message, variant) {
this.dispatchEvent(
new ShowToastEvent({
title,
message,
variant
})
);
}
}
</script>
<template>
<lightning-card title="Upload or Select File">
<div class="slds-m-around_medium">
<!-- Custom File Input to Validate File Before Upload -->
<input type="file" accept=".jpg,.jpeg,.png" onchange={handleFileChange} />
<!-- Hidden lightning-file-upload (Triggered Only If File Is Valid) -->
<lightning-file-upload
class="slds-hide"
label="Hidden File Upload"
record-id={recordId}
accept=".jpg,.jpeg,.png"
onuploadfinished={handleUploadFinished}
multiple>
</lightning-file-upload>
<!-- Select Existing File -->
<template if:true={files.length}>
<lightning-combobox
name="fileSelect"
label="Select Existing File"
options={files}
onchange={handleFileSelection}>
</lightning-combobox>
</template>
</div>
</lightning-card>
</template>
Restrict file uploads to only JPG, JPEG, and PNG file types
Reviewed by dasfrogpractice
on
10:19
Rating:
No comments: