0

I'm a javascript-writing novice...

Ben posted this on JavaScript file upload size validation that I'm using to detect pre-upload file size. Is there a way to insert some (math) function directly into the code that will limit the file size to two decimal places when the alert is presented?

<script type="text/javascript">
    $('#image-file').bind('change', function() {
        alert('This file size is: ' + this.files[0].size/1024/1024 + "MB");
    });
</script>
Community
  • 1
  • 1
WGD
  • 43
  • 1
  • 5

1 Answers1

3
alert('This file size is: ' + (this.files[0].size/1024/1024).toFixed(2) + "MB")

This is hardly specific to file size validation, it's just about number formatting in general.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Barmar's comment helped me realize that the alert is being triggered for every file (i.e., regardless of size). Ideally, I'd like to limit the alert so that it is only triggered if the file size exceeds my PHP $max_file_size (or an additional js variable?). Something like this perhaps would work? (I appreciate your patience with my apparent ineptness as a js coder.) – WGD May 11 '13 at 06:18
  • If the JS is in an HTML file created by PHP, you can write `if (size > )`. If you have trouble getting this to work, ask a new question. – Barmar May 11 '13 at 14:15
  • The $max_file_size is called in a PHP function when the form is submitted which is after the js has been triggered, so I thought something like this might work (for a 2M limit), but it doesn't. var size = 2097152; $('#userfile').bind('change', function() { if(size > 2097152); alert('The file size is ~ ' + (this.files[0].size/1024/1024).toFixed(2) + "MB which exceeds file upload limits."); } ); Am I even in the ballpark yet? Thanks again for your patience and assistance. – WGD May 11 '13 at 18:58
  • What part of "ask a new question" was unclear? `if (size > 2097152)` isn't checking the file size, since you just set the variable `size` to the same number. – Barmar May 11 '13 at 19:02
  • I'm sorry; I guess I misunderstood. Should I start a separate question in the forum? Thanks! – WGD May 11 '13 at 19:04
  • Yes, if you can't figure out how to get `var size = this.files[0].size` to work. – Barmar May 11 '13 at 19:22