This article introduces JQuery's code for obtaining and verifying the size of uploaded files. Previously, we used JavaScript to verify the size of uploaded files, but sometimes it is incompatible, later, I found a good JQuery function to get the size of the uploaded file and implement file size verification. For details, refer.
Jquery
The Code is as follows: |
Copy code |
/* * * Function to validate File size * **/ Function findSize (field_id) { Var fileInput = $ ("#" + field_id) [0]; ByteSize = fileInput. files [0]. fileSize; Return (Math. ceil (byteSize/1024); // Size returned in KB. } |
Put the code that I used to verify the size of the uploaded file in js. For more information, see.
The Code is as follows: |
Copy code |
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Strict // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <Html xmlns = "http://www.w3.org/1999/xhtml"> <Head> <Meta name = "DEscription" contect = "my code demo"/> <Meta name = "Author" contect = "Michael@www.micmiu.com"/> <Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/> </Head> <Body>
<Input type = "file" name = "file" id = "fileuploade" size = "40"/> <Input type = "button" name = "check" value = "checkfilesize" onclick = "checkfile ()"/> </Body> <Script type = "text/javascript"> Var maxsize = 2*1024*1024; // 2 M Var errMsg = "The uploaded attachment file cannot exceed 2 MB !!! "; Var tipMsg = "At present, your browser does not support calculating the size of the uploaded file. Make sure that the size of the uploaded file cannot exceed 2 MB. We recommend that you use IE, FireFox, and Chrome browsers. "; Var browserCfg = {}; Var ua = window. navigator. userAgent; If (ua. indexOf ("MSIE")> = 1 ){ BrowserCfg. ie = true; } Else if (ua. indexOf ("Firefox")> = 1 ){ BrowserCfg. firefox = true; } Else if (ua. indexOf ("Chrome")> = 1 ){ BrowserCfg. chrome = true; } Function checkfile (){ Try { Var obj_file = document. getElementById ("fileuploade "); If (obj_file.value = ""){ Alert ("Select Upload file first "); Return; } Var filesize = 0; If (browserCfg. firefox | browserCfg. chrome ){ Filesize = obj_file.files [0]. size; } Else if (browserCfg. ie ){ Var obj_img = document. getElementById ('tempimg '); Obj_img.dynsrc = obj_file.value; Filesize = obj_img.fileSize; } Else { Alert (tipMsg ); Return; } If (filesize =-1 ){ Alert (tipMsg ); Return; } Else if (filesize> maxsize ){ Alert (errMsg ); Return; } Else { Alert ("file size meets requirements "); Return; } } Catch (e ){ Alert (e ); } } </Script> </Html> |