[SalesForce] Limit file size apex:inputFile

Situation

I've implemented a simple VF form:

<apex:form>
    <apex:inputFile value="{!aFile}" />
    <apex:commandButton value="send" action="{!upload}" />
</apex:form>

Question

Is it possible to limit size (without hitting governor limits)?

Best Answer

Here's a solution using javascript. I'm also using jquery but you could modify it to select the apex:inputfile by its full ID and use vanilla javascript. It's using 500k as an arbitrary limit, but you can set it to whatever you want. The 'attachmentID' is the ID set on the apex:inputfile :

if ($("[id$='attachmentID']")[0].files.length > 0) {
    //validate file attachment is not > 500k
    var uploadFileSize = $("[id$='attachmentID']")[0].files[0].size;
    if (uploadFileSize > 1024 * 1024 * .5) {
        alert('File uploads must be less than 500k in size. Your file is: '+(Math.round(uploadFileSize/1024)) + 'k');
    }
    else {
        // call save method, passed validation
    }
}
else {
    // no file attached, if not required, call save method
}
Related Topic