anonymous-one
anonymous-one

Reputation: 15112

Maximum size of post file upload - any way to set via HTML?

So, we allow a few uploads to our web service.

Avatars and such.

We set the maximum size of these file uploads to 8MB via php's upload_max_filesize.

This works great, except that if a user uploads a larger image, for example 15MB, an error will be dumped in our php log.

We want to avoid this.

So:

Is there anyway to set via HTML the maximum upload size of a file so uploads over our specified size are not even sent to our server and thus, the error showing in the log is avoided?

Here is the PHP error we are trying to avoid BTW:

PHP Warning:  POST Content-Length of 11978117 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

Upvotes: 1

Views: 742

Answers (1)

Jukka K. Korpela
Jukka K. Korpela

Reputation: 201728

You cannot restrict the file size using HTML markup. (In very early days, RFC 1867 said that the maxlength attribute would do this, but this feature was never implemented or taken into HTML specs.)

However, reasonably modern browsers support the File API, which lets you code such checks using client-side JavaScript. Example:

<script>
function checkFiles(files) {
  var ok = true;
  if(files) {
    for (var i = 0; i < files.length; i++) {
      var file = files[i];
      if(file.size > 8 * 1024 * 1024) {
         alert("The file" + file.name + " is too big.");
         ok = false; } } }
  return ok;
}
</script>
[...]
<form action="..." method="post" onsubmit=
 "return checkFiles(document.getElementById('f').files)"
[...]
<div><label for="f">File(s):</label>
<input id="f" type="file" name="file" multiple></div>

Upvotes: 1

Related Questions