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
 
<html> 
<head> 
<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 
if(filepath){ 
var isnext = false; 
var fileend = filepath.substring(filepath.indexOf(".")); 
if(filetypes && filetypes.length>0){ 
for(var i =0; i<filetypes.length;i++){ 
if(filetypes[i]==fileend){ 
isnext = true; 
break; 
} 
} 
} 
if(!isnext){ 
alert(" This file type is not accepted! "); 
target.value =""; 
return false; 
} 
}else{ 
return false; 
} 
if (isIE && !target.files) { 
var filePath = target.value; 
var fileSystem = new ActiveXObject("Scripting.FileSystemObject"); 
if(!fileSystem.FileExists(filePath)){ 
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; 
if(size>filemaxsize){ 
alert(" Attachment size must not be greater than "+filemaxsize/1024+"M ! "); 
target.value =""; 
return false; 
} 
if(size<=0){ 
alert(" Attachment size cannot be 0M ! "); 
target.value =""; 
return false; 
} 
} 
</script> 
</head> 
<body> 
<input type="file" name="contractFileName" style="width: 500px;" onchange="fileChange(this);"/> 
</body> 
</html> 

Related articles: