Using Jquery, Restricting File Size Before Uploading

Restrict the image upload size to 20kb using jquery on client side

File sizes can be compared from within the change event handler and if it exceeds the input is cleared. It can also be done on submit.

$('input#file').bind('change', function() {  var maxSizeKB = 20; //Size in KB  var maxSize = maxSizeKB * 1024; //File size is returned in Bytes  if (this.files[0].size > maxSize) {    $(this).val("");    alert("Max size exceeded");    return false;  }});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="file">

JavaScript file upload size validation

Yes, you can use the File API for this.

Here's a complete example (see comments):

document.getElementById("btnLoad").addEventListener("click", function showFileSize() {
// (Can't use `typeof FileReader === "function"` because apparently it
// comes back as "object" on some browsers. So just see if it's there
// at all.)
if (!window.FileReader) { // This is VERY unlikely, browser support is near-universal
console.log("The file API isn't supported on this browser yet.");
return;
}

var input = document.getElementById('fileinput');
if (!input.files) { // This is VERY unlikely, browser support is near-universal
console.error("This browser doesn't seem to support the `files` property of file inputs.");
} else if (!input.files[0]) {
addPara("Please select a file before clicking 'Load'");
} else {
var file = input.files[0];
addPara("File " + file.name + " is " + file.size + " bytes in size");
}
});

function addPara(text) {
var p = document.createElement("p");
p.textContent = text;
document.body.appendChild(p);
}
body {
font-family: sans-serif;
}
<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load'>
</form>

How to have jQuery restrict file types on upload?

You can get the value of a file field just the same as any other field. You can't alter it, however.

So to superficially check if a file has the right extension, you could do something like this:

var ext = $('#my_file_field').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['gif','png','jpg','jpeg']) == -1) {
alert('invalid extension!');
}

jquery to verify file type and file size before submitting

I'd suggest the following:

$('input:file').change(
function(e) {
var files = e.originalEvent.target.files;
for (var i=0, len=files.length; i<len; i++){
console.log(files[i].fileName, files[i].type, files[i].fileSize);
}
});​

JS Fiddle demo.

As JavaScript can't remove files from the selected fileList object, you'd have to perform checks against the file attributes and prompt the user to deselect files that would be considered invalid due to file-type or file-size (and, obviously, prevent the form submitting):

$('input:file').change(
function(e) {
var files = e.originalEvent.target.files;
for (var i=0, len=files.length; i<len; i++){
var n = files[i].name,
s = files[i].size,
t = files[i].type;

if (s > 100) {
console.log('Please deselect this file: "' + n + '," it\'s larger than the maximum filesize allowed. Sorry!');
}
}
});​

JS Fiddle demo.

(This last code tested and working in Chromium 19 and Firefox 15, both on Ubuntu 11.04.)

How to check file input size with jQuery?

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

For the HTML below

<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

jquery file upload restricting number of files

Use maxNumberOfFiles here is documentation :

$('#fileuploadbasic').fileupload({

maxNumberOfFiles: 6

});

File size total and update counter

You need to return filesize from ParseFile function to foreach loop, and sum up all together. But remember - if you want to send multiple files, you need to select all of them at once.

Of course there must be some validation to check if selected files are bigger than 10MB.

  $(document).ready(function(){var maxSize = 10, // MB    currentSize = 0,    remainSize = 0;
$("#addFile").click(function() { $("#my_file").click();});
$("#my_file").change(function(e) { var files = e.target.files;
for (var i = 0, f; f = files[i]; i++) { if (ParseFile(f) === false) { alert('not enought space - there\'s only ' + remainSize.toFixed(2) + ' MB left'); break; } }
$('#totalsize span').text(currentSize.toFixed(2)); $('#remainsize span').text(remainSize.toFixed(2));
function ParseFile(file) { var filename = file.name.replace(/\..+$/, ''); var filesize = file.size / 1024; filesize = (Math.round((filesize / 1024) * 100) / 100); var filetype = file.type.split('/').pop().toUpperCase(); if (filetype == 'PDF' || filetype == 'JPEG' || filetype == 'JPG' || filetype == 'PNG') { if (currentSize + filesize >= maxSize) { return false; } currentSize += filesize; remainSize = maxSize - currentSize;
$("#filedetails").append("<tr><td><strong>" + filename + "</strong></td><td>" + filesize + " MB</td><td>" + filetype + "</td><td><a href='#'>Delete</td></tr>"); } else { alert('Only JPG, PDF n PNG files are allowed to upload.'); } }}); });
<!doctype html><html><head> <title>File Upload</title> <script src="https://code.jquery.com/jquery-3.1.0.min.js"></script> <script src="fileupload.js"></script></head><body> <input type="button" value="Add File(s)" id="addFile"> <input type="file" id="my_file" style="display:none;" multiple="multiple" accept="image/png, image/jpg, image/jpeg, application/pdf"> <table cellspacing="0" cellpadding="0" width="100%" border="1">  <thead>   <tr>    <th>Name</th>    <th>Size</th>    <th>Type</th>    <th></th>  </thead>  <tbody id="filedetails"></tbody> </table> <div id="totalsize">Total Uploaded File Size(s): <span>0</span> MB</div> <div id="remainsize">Remain: <span>0</span> MB</div></body></html>


Related Topics



Leave a reply



Submit