Sharepoint : Limit size attachment

Hello,
is it possible to check the size of the attachments uploaded and eventually get an error message before submit the form?
I want to limit attachments size to 10 mb (the total of all attachments must be less than 10 mb).
Thank you.

Hello @stefano.mazzi,

You can add custom validation to check the total file size of a newly uploaded files. Add this code inside the spRendered event:

fd.field('Attachments').ready(function(field) {
    field.validators.push({
        name: 'Check Attachment',
        error: "Error text attachments",
        validate: function(value) {
            let sum = 0;
            for (i = 0; i < value.length; i++) {
                sum += value[i].size;
                console.log(sum);

            }
            if (sum > '10485760') {
                this.error = "Max allowed total file size is 10Mb!"
                return false;
            }
            return true;
        }
    });
});

Hi @mnikitina,
thank you for your help!
In the meantime I tried with this script and seems to work.

fd.spRendered(function(){
        fd.field('Attachments').validators.push({
                name: 'Attachments Validation',
                error: "Attachments size limit exceeded. Max size up to 10 megabytes (MB)",
                validate: function(value) {
                  var totalSizeCheck = true;
                  var totalSize = 0;
                  value.forEach(function(file){
                    var size = file.size;
                    console.log('Size = ' + size);
                    totalSize = totalSize + size;
                    console.log('Total Size = ' + totalSize + ' of 10485760');
                    if (totalSize > '10485760') {
                      totalSizeCheck = false
                    }
                  })
                  return totalSizeCheck;
                }
        });
});

What do you think?
Could be valid or would be better use your code?

@stefano.mazzi,

Works great! Nice job! Thank you for sharing :purple_heart:

You are welcome!
Always thanks for your help!

1 Like