Using jQuery, Restricting File Size Before Uploading

JavascriptJqueryImageJquery PluginsUpload

Javascript Problem Overview


On PHP, they have a way to restrict file size AFTER uploading, but not BEFORE uploading. I use the Malsup jQuery Form Plugin for my form posting, and it supports image file posting.

I was wondering if perhaps there's a restriction where I can set how many bytes can pass through that AJAX stream up to the server? That could permit me to check that file size and return an error if the file is too big.

By doing this on the client side, it blocks those newbies who take a 10MB photo shot from their Pentax and try to upload that.

Javascript Solutions


Solution 1 - Javascript

This is a copy from my answers in a very similar question: https://stackoverflow.com/questions/1601455/check-file-input-size-with-jquery/3937404#3937404


You actually don't have access to the filesystem (for example reading and writing local files). However, due to the HTML5 File API specification, there are some file properties that you do have access to, and the file size is one of them.

For this HTML:

<input type="file" id="myFile" />

try the following:

//binds to onchange event of your input field
$('#myFile').bind('change', function() {
  //this.files[0].size gets the size of your file.
  alert(this.files[0].size);
});

As it is a part of the HTML5 specification, it will only work for modern browsers (v10 required for IE) and I added here more details and links about other file information you should know: http://felipe.sabino.me/javascript/2012/01/30/javascipt-checking-the-file-size/


Old browsers support

Be aware that old browsers will return a null value for the previous this.files call, so accessing this.files[0] will raise an exception and you should check for File API support before using it

Solution 2 - Javascript

I don't think it's possible unless you use a flash, activex or java uploader.

For security reasons ajax / javascript isn't allowed to access the file stream or file properties before or during upload.

Solution 3 - Javascript

I tried it this way and I am getting the results in IE*, and Mozilla 3.6.16, didnt check in older versions.

<img id="myImage" src="" style="display:none;"><br>
<button onclick="findSize();">Image Size</button>
<input type="file" id="loadfile" />
<input type="button" value="find size" onclick="findSize()" />
<script type="text/javascript">
function findSize() {
    if ( $.browser.msie ) {
   	   var a = document.getElementById('loadfile').value;
		   $('#myImage').attr('src',a);
		   var imgbytes = document.getElementById('myImage').size;
		   var imgkbytes = Math.round(parseInt(imgbytes)/1024);
		   alert(imgkbytes+' KB');
	}else {
		   var fileInput = $("#loadfile")[0];
		   var imgbytes = fileInput.files[0].fileSize; // Size returned in bytes.
		   var imgkbytes = Math.round(parseInt(imgbytes)/1024);
				   alert(imgkbytes+' KB');
	 }
}    
</script>

Add Jquery library also.

Solution 4 - Javascript

I encountered the same issue. You have to use ActiveX or Flash (or Java). The good thing is that it doesn't have to be invasive. I have a simple ActiveX method that will return the size of the to-be-uploaded file.

If you go with Flash, you can even do some fancy js/css to cusomize the uploading experience--only using Flash (as a 1x1 "movie") to access it's file uploading features.

Solution 5 - Javascript

I found that Apache2 (you might want to also check Apache 1.5) has a way to restrict this before uploading by dropping this in your .htaccess file:

LimitRequestBody 2097152

This restricts it to 2 megabytes (2 * 1024 * 1024) on file upload (if I did my byte math properly).

Note when you do this, the Apache error log will generate this entry when you exceed this limit on a form post or get request:

Requested content-length of 4000107 is larger than the configured limit of 2097152

And it will also display this message back in the web browser:

<h1>Request Entity Too Large</h1>

So, if you're doing AJAX form posts with something like the Malsup jQuery Form Plugin, you could trap for the H1 response like this and show an error result.

By the way, the error number returned is 413. So, you could use a directive in your .htaccess file like...

Redirect 413 413.html

...and provide a more graceful error result back.

Solution 6 - Javascript

 $(".jq_fileUploader").change(function () {
    var fileSize = this.files[0];
    var sizeInMb = fileSize.size/1024;
    var sizeLimit= 1024*10;
    if (sizeInMb > sizeLimit) {
      

    }
    else {

       
    }
  });

Solution 7 - Javascript

Like others have said, it's not possible with just JavaScript due to the security model of such.

If you are able to, I'd recommend one of the below solutions..both of which use a flash component for the client side validations; however, are wired up using Javascript/jQuery. Both work very well and can be used with any server-side tech.

http://www.uploadify.com/

http://swfupload.org/

Solution 8 - Javascript

Try below code:

var sizeInKB = input.files[0].size/1024; //Normally files are in bytes but for KB divide by 1024 and so on
var sizeLimit= 30;

if (sizeInKB >= sizeLimit) {
    alert("Max file size 30KB");
    return false;
}

Solution 9 - Javascript

It's not possible to verify the image size, width or height on the client side. You need to have this file uploaded on the server and use PHP to verify all this info. PHP has special functions like: getimagesize()

list($width, $height, $type, $attr) = getimagesize("img/flag.jpg");
echo "<img src=\"img/flag.jpg\" $attr alt=\"getimagesize() example\" />";

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMike McKeeView Question on Stackoverflow
Solution 1 - JavascriptFelipe SabinoView Answer on Stackoverflow
Solution 2 - JavascriptTodd SmithView Answer on Stackoverflow
Solution 3 - JavascriptAbhilash RSView Answer on Stackoverflow
Solution 4 - JavascriptEndangeredMassaView Answer on Stackoverflow
Solution 5 - JavascriptMike McKeeView Answer on Stackoverflow
Solution 6 - JavascriptShemeemsha R AView Answer on Stackoverflow
Solution 7 - JavascriptJamesEggersView Answer on Stackoverflow
Solution 8 - JavascriptBablu AhmedView Answer on Stackoverflow
Solution 9 - JavascriptAdrianView Answer on Stackoverflow