Sample code that determines the type and size of the uploaded file

  • 2020-03-26 21:28:14
  • OfStack

 
//Detects file size and type
function fileChange(target){ 
//Detects the type of uploaded file
if(!(/(?:jpg|gif|png|jpeg)$/i.test(target.value))) { 
alert(" Upload only allowed jpg|gif|png|jpeg Format picture "); 
if(window.ActiveXObject) {//for IE 
target.select();//select the file ,and clear selection 
document.selection.clear(); 
} else if(window.opera) {//for opera 
target.type="text";target.type="file"; 
} else target.value="";//for FF,Chrome,Safari 
return; 
} else { 
return; //alert("ok");//or you can do nothing here. 
} 

//Detects the size of the uploaded file
var isIE = /msie/i.test(navigator.userAgent) && !window.opera; 
var fileSize = 0; 
if (isIE && !target.files){ 
var filePath = target.value; 
var fileSystem = new ActiveXObject("Scripting.FileSystemObject"); 
var file = fileSystem.GetFile (filePath); 
fileSize = file.Size; 
} else { 
fileSize = target.files[0].size; 
} 
var size = fileSize / 1024; 
if(size>(500)){ 
alert(" The file size cannot exceed 500KB"); 
if(window.ActiveXObject) {//for IE 
target.select();//select the file ,and clear selection 
document.selection.clear(); 
} else if(window.opera) {//for opera 
target.type="text";target.type="file"; 
} else { 
target.value="";//for FF,Chrome,Safari 
} 
return; 
}else{ 
return; 
} 
} 

Related articles: