代码之家  ›  专栏  ›  技术社区  ›  Kunal Vijan

文件大小总计和更新计数器

  •  1
  • Kunal Vijan  · 技术社区  · 9 年前

    我需要计算上传文件的总大小,然后将其从10减小为10MB,因为总可用限制仅为10MB。每次上传/添加文件时,应减少剩余空间。 例如,初始限制为10 MB。我上传了一个3MB的文件,剩下7MB。现在又有一个4MB的文件,剩余的应该是3MB。

    问题:我可以在上传过程中禁用文件上传按钮吗?即使有任何文件正在上传,也应禁用该功能,并仅在所有文件上传完毕后才允许添加其他文件。

    $(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>
    1 回复  |  直到 9 年前
        1
  •  1
  •   jacqbus    9 年前

    当然,必须进行一些验证,以检查所选文件是否大于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>

    编辑: 下面是上述代码的扩展版本,实现了“删除”功能。 重构是非常明智的。

    $(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>