I have a Lightning file Upload component I am using Lightning:fileupload . so user tries to upload more than 100MB. I want to show an error message, it is possible?
2 Answers
I can't see such a feature being supported out of the box looking at the specifications for Aura File Upload. The supported attributes are:
- accept
- body
- class
- disabled
- label
- multiple
- name
- onuploadfinished
- recordId
- title
-
-
I can't think of a way since the file upload is handled by salesforce so you don't get access to the file to see its filesize.– ArthleteJul 1, 2020 at 3:39
I had a similar requirement but using LWC and what I did was, allowed the User to upload the 100MB file but then check the document size, if it was greater than XXX MB, I deleted the file and showed an error message.
Example code:
HTML:
<lightning-file-upload label="" onuploadfinished={uploadFile}
</lightning-file-upload>
JS:
async handleUpload(event) {
const fileUploaded = event.detail.files;
try {
const file = fileUploaded[0];
const checkDocSize = await getDocumentSize({docId : file.documentId});
if(checkDocSize == true) {
const toastEvent = new ShowToastEvent({
message: 'File cannot be uploaded as it exceeds the maximum size of 5MB',
variant: 'error'
});
this.dispatchEvent(toastEvent);
const docDeleted = await deleteDocument({fileId : file.documentId});
}
else {
const toastEvent = new ShowToastEvent({
message: 'File uploaded successfully',
variant: 'success'
});
}
} catch(e) {
console.error('Error during file upload:',error);
}
}
Apex:
@AuraEnabled
public static Boolean getDocumentSize(String docId) {
List<ContentDocument> documentList = [SELECT Id, Title, ContentSize FROM ContentDocument WHERE Id = :docId WITH SECURITY_ENFORCED];
Boolean sizeExceeded = false;
try{
if(!documentList.isEmpty()) {
Decimal contentSize = documentList[0].ContentSize;
Decimal fileSize = (contentSize / (1024.0*1024.0)).setScale(2);
if(fileSize > 5 ) {
return true;
}
return false;
}
} catch(Exception e){
throw new AuraHandledException(e.getMessage());
}
}
@AuraEnabled
public static void deleteDocument(String docId) {
List<ContentDocument> docToBeDeleted = [SELECT Id FROM ContentDocument WHERE Id = :docId];
try{
if(!docToBeDeleted.isEmpty()) {
delete docToBeDeleted;
}
} catch(Exception e){
throw new AuraHandledException(e.getMessage());
}
}
-
Please elaborate on how you did that. Did you check the file size on a trigger or on the front-end? A snippet of your code used to do this would also be beneficial. :) Aug 7 at 22:09
-