When we upload files, in order to achieve the effect of asynchronous upload, we usually choose to upload files in the form of iframe, but we cannot process the data returned by the server like ajax to adjust the file size and file style. Judgment, so we generally think of using js to make a preliminary judgment on the size and format of the uploaded file, and then make another judgment on the server (to prevent the browser from refusing to execute the script file).
The following provides a method to use js to determine the 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 image format is incorrect
'
'Audio format is incorrect
'
'Video format is incorrect
',
"1" : 'Picture format is incorrect',
"2" : 'Audio format is incorrect',
"3" : 'Video format is incorrect'
};
var errSizeMsg = {
'1': 'Picture file is less than 2M ',
'2':'Audio file is less than 5M',
'3':'Video file is 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 to be uploaded');
return false;
}
if (!checkFileType(filename, type) ){
alert('The file format is incorrect');
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, obj is the upload control itself (this)