Js determines the upload file size and format code

  • 2020-03-29 23:45:25
  • OfStack

We was in a file upload, in order to achieve the effect of asynchronous upload, would use the iframe form for file upload, but we can't like ajax server returned data for processing, thus to file size, and style of judgment, so we usually think of use js to upload the file size and format for a preliminary judgment, again on the server (to prevent the browser refuses to execute the script file).
The following provides a way to use js to determine file size.
 
var url = window.location.href, type = url.substr(url.lastIndexOf('/')+1); 
// console.log(type); 
var allowType = { 
".bmp":1, ".png":1, ".jpeg":1, ".jpg":1, ".gif":1, 
".mp3":2, ".wma":2, ".wav":2, ".amr":2, 
".rm":3, ".rmvb":3, ".wmv":3, ".avi":3, ".mpg":3, ".mpeg":3, ".mp4":3 
}; 
var allowSize = {1:2097152, 2:5242880, 3:20971520}; 
var errMsg = { 
"0" : ' The picture format is incorrect <br/>' 
+ ' The audio format is incorrect <br/>' 
+ ' The video is not formatted correctly <br/>', 
"1" :  'the picture is not in the right format ', 
"2" : ' The audio format is incorrect ', 
"3" : ' The video is not formatted correctly ' 
}; 
var errSizeMsg = { 
'1':' Image file less than 2M', 
'2':' Audio file less than 5M', 
'3':' Video file less than 20M', 
} 
function checkFileType(filename, type){ 
var ext = filename.substr(filename.lastIndexOf(".")).toLowerCase(), 
res = allowType[ext]; 
if (type == 0) { 
return !!res; 
} else { 
return type == res; 
} 
} 
function checkFileSize(target, size){ 
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 fsize = fileSize / 1024*1024; 
if(parseInt(fsize) >= parseInt(size)){ 
return false; 
}else{ 
return true; 
} 
} 
function upload(obj){ 
var filename = jQuery.trim(jQuery('#uploadFile').val()); 
if (!filename || filename == ""){ //Recheck before submission
alert(' Select the file you want to upload '); 
return false; 
} 
if (!checkFileType(filename, type)){ 
alert(' Incorrect file format '); 
return false; 
} 
var ext = filename.substr(filename.lastIndexOf(".")).toLowerCase(); 
var res = allowType[ext]; 
if(!checkFileSize(obj,allowSize[res])){ 
alert(errSizeMsg[res]); 
return false; 
} 
//Other processing
} 
//UploadFile is the id of the upload control and obj is the upload control itself (this)

Related articles: