0

I have an <apex:inputFile> in an apex repeat. I do a check on the <apex:inputFile> with javascript. This seems only to be working for the first <apex:inputFile>. How do I manage to get this to work for the repeats.

Repeat:

<apex:repeat value="{!newAttachments}" var="newAtt">
                    <apex:outputLabel value="Upload file"/>                      
                    <apex:inputFile id="inputfile" value="{!newAtt.body}" filename="{!newAtt.name}"  onchange="checkFileSize(event)" />
                </apex:repeat>

Script:

<script>
        function checkFileSize(event){
            if ($("[id$=inputfile]")[0].files.length > 0) {
                //validate file attachment is not > 500k
                var uploadFileSize = $("[id$=inputfile]")[0].files[0].size;
                if (uploadFileSize > 1024 * 1024 * .5) {
                    alert('File uploads must be less than 500k in size. remove files over: '+(Math.round(uploadFileSize/1024)) + 'k');
                    event.preventDefault();
                }
                else {
                    //  
                }
            }
            else {
                // no file attached, if not required, call save method
            }
        }
        </script> 
2

Use event.target to check the correct element:

function checkFileSize(event) {
  if(event.target.files && event.target.files[0]) {
    if(event.target.files[0].size > 2**19) {
      alert('File must be less than 500kb');
    } else {
      // ...
    }
  }
}

There's no need to use jQuery here.

  • Could you please explain the 2**19 part? – Thomas Dec 19 '18 at 12:40
  • It's 2 to the 19th power, which is the same as 1024 * 1024 * .5 but with a lot less typing. – sfdcfox Dec 19 '18 at 12:47

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.