Kunal Vijan Kunal Vijan - 3 months ago 8
jQuery Question

File size total and update counter

I need to calculate the total size of uploaded files and then reduce it from 10 as total available limit is 10MB only. Each time file upload/add it should reduce from remaining space.
For e.g. Initial limit 10 MB. I uploaded 1 file of 3 MB, remaining 7 MB. Now another file of 4 MB so, remaining should be 3 MB.



$(document).ready(function(){
$("#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++) {
ParseFile(f);
}
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') {
$("#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): </div>
</body>
</html>




Answer

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>

EDIT: Below is extended version of above code with 'delete' function implemented. Refactoring is highly advisable.

$(document).ready(function(){

var maxSize = 10, // MB
		currentSize = 0,
		remainSize = 0;

function refreshSpace() {
	$('#totalsize span').text(currentSize.toFixed(2));
	$('#remainsize span').text(remainSize.toFixed(2));
}

$("#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;
		}
	}

	refreshSpace();

	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 data-filesize='" + filesize + "'><td><strong>" + filename + "</strong></td><td>" + filesize + " MB</td><td>" + filetype + "</td><td><a class='delete' href='#'>Delete</td></tr>");
		}
		else {
			alert('Only JPG, PDF n PNG files are allowed to upload.');
		}
	}
});

$("#filedetails").on('click', '.delete', function(e) {
	var $parent = $(this).closest('tr'),filesize = $parent.attr('data-filesize');
	currentSize -= filesize;
	remainSize = maxSize - currentSize;
	refreshSpace();
	$parent.remove();
});
});
<!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.00</span> MB</div>
	<div id="remainsize">Remain: <span>10.00</span> MB</div>
</body>
</html>