During file upload, in order to achieve the asynchronous upload effect, iframe is usually used for file upload, but we cannot process the data returned by the server like ajax, so as to determine the file size and file style, we generally think of using js to make a preliminary judgment on the size and format of the uploaded file, make another judgment on the server (to prevent the browser from rejecting the script file ).
The following provides a method to determine the file size using js.
Copy codeThe Code is as follows:
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": 'incorrect image format <br/>'
+ 'Audio format incorrect <br/>'
+ 'Incorrect video format <br/> ',
"1": 'incorrect image format ',
"2": 'audio format incorrect ',
"3": 'invalid video format'
};
Var errSizeMsg = {
'1': 'image file less than 2 Ms ',
'2': 'audio file less than 5 ',
'3': 'video file smaller 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 = "") {// re-check before submission
Alert ('select the file to be uploaded ');
Return false;
}
If (! CheckFileType (filename, type )){
Alert ('file format 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 upload Control id, and obj is the upload control's own (this)