Análisis de requisitos:
Al subir imágenes, si el tamaño de la imagen cargado no se limita, las consecuencias serán muy graves. Entonces, ¿cómo podemos resolver un problema difícil? Hay dos formas:
1) Procesamiento de back -end: es decir, AJAX Post se envía al fondo, cargue la imagen en el servidor y luego obtenga el tamaño de la imagen para el procesamiento.
2) Procesamiento de recepción: es decir, use JavaScript para obtener el tamaño de la imagen.
Obviamente, el primer método no es bueno. Debido a que primero debe cargar el archivo al servidor, si el archivo es grande, la red no será muy rápida y debe esperar mucho tiempo para tratar los síntomas, pero no la causa raíz.
Análisis funcional:
Aquí solo presentaré las diferentes prácticas de los navegadores IE y Firefox.
IE6:
Palabra clave: fileSize OnreadyStateChange Complete
En IE6, el tamaño del archivo se puede obtener a través de la propiedad de tamaño de archivo del objeto IMG, pero el valor correcto de esta propiedad de tamaño de archivo está integrado en el evento OnreadyStateChange, es decir, es,
<img src = "" onreadyStateChange = "javaScript: SizeCheck (this);"> función SizeCheck (img) {if (img.readyState == "Complete") {alert (img.filesize); }}Firefox 3.0:
Palabra clave: getAsdataurl () filesize
En Firefox, no es posible obtener la ruta completa para cargar la imagen, solo se puede obtener el nombre de la imagen. Sin embargo, el navegador proporciona una interfaz NSIDOMFILE, por lo que debe obtener la ruta procesada a través de getAsDataurl (), pero esta ruta no afecta la visualización de la imagen SRC.
Interfaz NSIDOMFILE:
Domstring getAsbinary (); Domstring getasdataurl (); Domstring getastext (en la codificación de domstring); <input type = "file" name = "uploadImg" onChange = "javaScript: checkFiLechange (this);" size = "12"/> function checkFiLechange (obj) {var img = document.getElementById ("img"); img.src = obj.files [0] .getAsdataurl (); alerta (obj.files [0] .filesize); }Los anteriores son los métodos de procesamiento de dos navegadores diferentes, entonces, ¿cómo los integran juntos? Publicaré el pequeño ejemplo que hice a continuación, donde uso jQuery para facilitar la adquisición de objetos
< xmlns = "http://www.w3.org/1999/xhtml" xml: lang = "zh" lang = "zh" dir = "ltr"> <head> <meta http-equiv = "content-type" content = "text/html; charset = utf-8"/> <script type = "text" src = "lib/jQuery-1.3.2.min.js"> </script> <title> Verifique el tamaño de imagen cargado </title> <style type = "text/css"> .img {width: 136px; Height: 102px;} .imgerror {borde: 3px sólido rojo;} </sytle> <script type = "text/javaScription" var maxSize = 100 * 1024; // Información de límite de tamaño de imagen VAR ERROR_IMGSIZE = "El tamaño de la imagen no puede exceder 100k"; // imagen predeterminada var nofoto = "imgs/nophoto.gif"; // es la imagen calificada var isimg = true; /*** Evento de entrada de archivo Onchange* @params Obj File Object* @return void **/function checkFiLechange (obj) {// Inicializar configuración $ (". ImgTable"). RemoveClass ("imgerRor"); UpdateTips (""); var img = $ (". img"). get (0); archivo var = obj.value; var exp = /./.jpg|./.gif|./.png|./.bmp/i; if (exp.test (file)) {// verificar formato if ($. browser.msie) {// juzga si es IE img.src = file; } else {img.src = obj.files [0] .getAsdataurl (); Sizecheck (img); }} else {img.src = nophoto; $ (". imgTable"). addClass ("imgerror"); UpdateTips ("El formato IMG es incorrecto"); isimg = falso; }} /*** SizeCheck Verifique el tamaño de la imagen* @params img Objeto de imagen* @return void ** /function sizeCeck (img) {// inicializar la configuración $ (". imgtable"). removeclass ("imgerror"); UpdateTips (""); if ($ .browser.msie) {// vea si es IE if (img.readyState == "completo") {if (img.filesize> maxsize) {$ (". imgtable"). addClass ("imgerror"); UpdateTips (ERROR_IMGSIZE); isimg = falso; } else {isimg = true; }} else {$ (". imgTable"). addClass ("imgerror"); UpdateTips (ERROR_IMGSIZE); isimg = falso; } else {isimg = true; }} else {$ (". imgTable"). addClass ("imgerror"); UpdateTips (ERROR_IMGSIZE); isimg = falso; }} else {var file = $ ("input: file [name = 'uploadImg']") [0]; if (file.files [0] .filesize> maxSize) {$ (". imgTable"). addClass ("imgerRor"); UpdateTips (ERROR_IMGSIZE); isimg = falso; } else {isimg = true; }}} / *** UpdateTips Mensaje de error de registro Pantalla* @Params Str Muestre contenido* @return void ** / function updateTips (str) {$ ("P#errortips"). Text (str); } / *** Commit Registro y envío* @return void ** / function commit () {var isCommit = true; var usrname = $ ("input: text [name = 'usrname']"), email = $ ("input: text [name = 'email']"), img = $ (". img"), file = $ ("input: file [name = 'uploadimg']"), frm = document.frm; isCommit = isCommit && isImg; if (isCommit) {frmmMaaction = "About: Blank"; frM.Submit (); }} / *** Error de error ErrorImg Pantalla* @params img Object de imagen* @return void ** / function errorimg (img) {img.src = nophoto; } </script> </head> <body> <form de formular = "frm" método = "post"> <p id = "errortips"> </p> <table cellPadding = "1" celular = "0"> <tr> <tr> <td> <label> name: </etiqueta> </td> <td> <input type = "text" name = "usrname" maxlength longitud </tr> <tr> <tr> <td> <label> género: </selebel> </td> <td> <input type = "radio" name = "sex" value = "0"/> macho <input type = "radio" name = "sex" valor = "0"/> femenino </td> </tr> <tr> <tr> <td <td> <lelebel> email: </slabe> </td> <td> <TD <py type " maxLength = "100"/> </td> </tr> <tr> <tr> <td> <lable> imagen </label> </td> <td> <td> <table cellPadding = "0" celular = "0"> <tr> <tr> <td> <img src = "imgs/nophoto.gif" src = "imgs/nophoto.giF.giF.giF.giFi.giFiM" OneError = "JavaScript: ErrorImg (this);" OnReadyStateChange = "JavaScript: SizeCheck (this);"/> </td> </tr> <tr> <tr> <td> <input type = "file" name = "uploadImg" onChange = "javaScript: checkFileChange (this);" size = "12"/> </td> </tr> </box> </td> </tr> <tr> <td colspan = "2"> <a href = "javascript: commit ();" rel = "nofollow externo" rel = "externo nofollow" href = "javascript: commit ();" rel = "nofollow externo" rel = "externo nofollow"> registrar </a> </td> </tr> </table> </form> </body> </html>