Restrict attachments size on single catalog item

MonicaW
Tera Guru

I have a catalog item where we want to restrict the size of all attachments to 12 MB total.  I tried using the attachment variable, but it only allows the selection of ONE attachment.  I want the ability to add multiple attachments using the built-in "add attachments" on the catalog item itself and have it calculate the size of all of them and restrict it to 12 MB.

 

I found the following code that I put in an onSubmit script, but it's not working - perhaps I need to change more elements than the var maxAttachmentSizeMB = 12; line?

>>>>>>>>>>>>>>>>>>>>>>>>>

function onSubmit() {
var attachments = this.angular.element("#sc_cat_item").scope().attachments; // Adjust element ID as needed
var submitForm = false;
var maxAttachmentSizeMB = 12; // Set your desired limit in MB

attachments.forEach(function(attachment){
var sizeBytes = parseInt(attachment.size_bytes);
var sizeMB = sizeBytes / (1024 * 1024); // Convert bytes to MB.
var sizeString = String(attachment.size_bytes); // Get the size as a string to include the units
alert(sizeString);

if(sizeMB > maxAttachmentSizeMB){
alert(attachment.file_name + ' is too large. Maximum allowed size is ' + maxAttachmentSizeMB + ' MB.');
submitForm = false;
}
});
return submitForm;
}

20 REPLIES 20

Sorry, I'm on a Mac - what key combination would work?

@Rafael Batistot 

the script include function you shared doesn't check the catalog item which is getting submitted, then how it will know which sys_attachment to query and validate?

there could be different users submitting catalog item at the same time and add file and the script might pick that GlideRecord as well.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

@Ankur Bawiskar 

You're right, it's not possible to link the attached file to the catalog that sent it. That was a method I found, but you're right, there's a risk of others sending files at the same time. Well-observed.

@MonicaW

To open the console in Chrome on a Mac,press Cmd+Option+J or Cmd+Option+I.In Safari, first enable the "Develop" menu by going to Safari > Preferences > Advanced and checking the "Show Develop menu in menu bar" box, then press  Cmd+Option+C to open

You when you facing this issue msg go to console and show the error msg

RafaelBatistot_0-1758041785314.png

 




I figured out how to open the console yesterday and sent the results.  But here it is again (attached).

Ankur Bawiskar
Tera Patron
Tera Patron

@MonicaW 

there is a hack to it, you can grab the complete text from here, extract the file size and then sum up

For this you might require DOM manipulation which is not recommended.

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader