2

I have a apex:inputFile tag to upload a file I gave it an id to throw an error if the filesize exceeds 500k. The error is thrown but still I can see in my left corner of my chrome browser an attempt to upload the file. How do I abort this process.

Now I have to wait for the whole upload process.

 <apex:repeat value="{!newAttachments}" var="newAtt">
                    <apex:outputLabel value="Upload photo"/>                         
                    <apex:inputFile id="inputfile" value="{!newAtt.body}" filename="{!newAtt.name}"/><br/>
                </apex:repeat><br/>
                <apex:commandButton value="Add More" action="{!addMore}"  onclick="checkFileSize();"/>
 <script>
    function checkFileSize(){
    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. Your file is: '+(Math.round(uploadFileSize/1024)) + 'k');
    }
    else {

    }
}
else {
    // no file attached, if not required, call save method
}
        }
    </script> 
2

You need to prevent the default action in order to prevent the submission:

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 > 2**19) {
      alert('File uploads must be less than 500k in size. Your file is: '+(uploadFileSize>>10) + 'k');
      event.preventDefault();
    }
    // ... rest of code

Pass the event in through the onclick handler:

onclick="checkFileSize(event);"
  • Thanks, been struggeling with this one quite a while to figure out. – Thomas Dec 11 '18 at 19:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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