Client side js determines the file type and file size which limits the upload size

  • 2020-03-29 23:53:40
  • OfStack

Due to project needs! Need scripts to determine the size and file type on the client side! Oneself look for data to look for very hard on the net! Simply wrote and tested a file upload size limit of an example, compatible with ie6, ie7, ie8, Google Chrome, ff and other browsers
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<script type="text/javascript"> 
var isIE = /msie/i.test(navigator.userAgent) && !window.opera; 
function fileChange(target,id) { 
var fileSize = 0; 
var filetypes =[".jpg",".png",".rar",".txt",".zip",".doc",".ppt",".xls",".pdf",".docx",".xlsx"]; 
var filepath = target.value; 
var filemaxsize = 1024*2;//2M 
var isnext = false; 
var fileend = filepath.substring(filepath.indexOf(".")); 
if(filetypes && filetypes.length>0){ 
for(var i =0; i<filetypes.length;i++){ 
isnext = true; 
alert(" This file type is not accepted! "); 
target.value =""; 
return false; 
return false; 
if (isIE && !target.files) { 
var filePath = target.value; 
var fileSystem = new ActiveXObject("Scripting.FileSystemObject"); 
alert(" The attachment does not exist, please enter again! "); 
return false; 
var file = fileSystem.GetFile (filePath); 
fileSize = file.Size; 
} else { 
fileSize = target.files[0].size; 

var size = fileSize / 1024; 
alert(" Attachment size must not be greater than "+filemaxsize/1024+"M ! "); 
target.value =""; 
return false; 
alert(" Attachment size cannot be 0M ! "); 
target.value =""; 
return false; 
<input type="file" name="contractFileName" style="width: 500px;" onchange="fileChange(this);"/> 

Related articles: