Análise de requisitos:
Ao fazer o upload de fotos, se o tamanho da imagem carregado não for limitado, as consequências serão muito sérias. Então, como podemos resolver um problema difícil? Existem duas maneiras:
1) Processamento de back -end: Ou seja, o Ajax Post é enviado ao plano de fundo, carregue a imagem para o servidor e obtenha o tamanho da imagem para processamento.
2) Processamento da recepção: isto é, use JavaScript para obter o tamanho da imagem.
Obviamente, o primeiro método não é bom. Como você precisa fazer o upload do arquivo para o servidor primeiro, se o arquivo for grande, a rede não será muito rápida e você precisará esperar muito tempo para tratar os sintomas, mas não a causa raiz.
Análise funcional:
Aqui vou apresentar apenas as diferentes práticas dos navegadores do IE e do Firefox.
IE6:
Palavra -chave: FileSize OnreadyStatechange completo
No IE6, o tamanho do arquivo pode ser obtido através da propriedade FileSize do objeto IMG, mas o valor correto desta propriedade FileSee é incorporado no evento completo do evento OnreadyStateChange, ou seja,
<img src = "" oNreadyStatechange = "javascript: sizecheck (this);"> função sizecheck (img) {if (img.readyState == "complete") {alert (img.filesize); }}Firefox 3.0:
Palavra -chave: GetasDataurl () FileSee
No Firefox, não é possível obter o caminho completo para fazer upload da imagem, apenas o nome da imagem pode ser obtido. No entanto, o navegador fornece uma interface nsidomfile, portanto, você precisa obter o caminho processado através do getasDataurl (), mas esse caminho não afeta a exibição da imagem SRC.
Interface nsidomfile:
Domstring getasBinary (); Domstring getasdataurl (); Domstring getastext (na codificação Domstring); <input type = "file" name = "uploadimg" onchange = "javascript: checkFileChange (this);" size = "12"/> função checkFileChange (obj) {var iMg = document.getElementById ("img"); img.src = obj.files [0] .GetasDataurl (); alerta (obj.files [0] .Filesize); }O exposto acima são os métodos de processamento de dois navegadores diferentes, então como você os integra? Vou postar o pequeno exemplo que fiz abaixo, onde uso jQuery para facilitar a aquisição de objetos
<! xmlns = "http://www.w3.org/1999/xhtml" xml: lang = "zh" lang = "zh" dir = "ltr"> <head> <meta http-equiv = "content-ttype" = "text/html; charset = utf-utf-8" src = "lib/jQuery-1.3.2.min.js"> </script> <title> Verifique o tamanho da imagem carregado </ititle> <style type = "text/css"> .img {width: 136px; altura: 102px;} .imgerror {borda: 3px sólido Red; 100k var maxsize = 100 * 1024; // Informações do limite do tamanho da imagem var error_imgsize = "O tamanho da imagem não pode exceder 100k"; // imagem padrão var nophoto = "imgs/nofoto.gif"; // é a imagem qualificada var isimg = true; /*** Arquivo de entrada Evento OnChange* @params Object Obj de arquivo* @return void **/função checkFileChange (obj) {// Inicialize a configuração $ (". Imgtable"). Removeclass ("imgerror"); UpdateTips (""); var iMg = $ (". img"). Get (0); var arquivo var = obj.value; var exp = /./.jpg|./.gif|./.png|./.bmp/i; if (exp.Test (file)) {// Verifique o formato if ($. Browser.msie) {// julgue se é ie img.src = file; } else {img.src = obj.files [0] .GetasDataurl (); Sizecheck (IMG); }} else {img.src = nofoto; $ (". imgtable"). addclass ("imgerror"); UpdateTips ("formato img está incorreto"); isimg = false; }} /*** Sizecheck Tamanho da imagem* @params Objeto de imagem img* @return void ** /função sizecheck (img) {// inicialize a configuração $ (". imgtable"). removeclass ("imgerror"); UpdateTips (""); if ($ .browser.msie) {// veja se é ie if (img.readyState == "complete") {if (img.filesize> maxsize) {$ (". imgtable"). addclass ("imgerror"); updateTips (error_imgsize); isimg = false; } else {iSimg = true; }} else {$ (". imgtable"). addclass ("imgerror"); updateTips (error_imgsize); isimg = false; } else {iSimg = true; }} else {$ (". imgtable"). addclass ("imgerror"); updateTips (error_imgsize); isimg = false; }} else {var file = $ ("input: arquivo [name = 'uploadImg']") [0]; if (file.files [0] .Filesize> maxSize) {$ (". imgtable"). addclass ("imgerror"); updateTips (error_imgsize); isimg = false; } else {iSimg = true; }}} / *** Atualizações de erro de erro de registro de atualizações* @params str Exibir conteúdo* @return void ** / função updateTips (str) {$ ("p#errorTips"). text (str); } / *** CONFIGURAÇÃO REGISTRO E ENVIAR* @RETURN VOID ** / FUNÇÃO COMMIT () {var isCommit = true; var usrname = $ ("entrada: texto [nome = 'usrname']"), email = $ ("entrada: text [name = 'email']"), img = $ (". img"), arquivo = $ ("entrada: arquivo [name = 'uploadimg']"), frm = document.frm; isCommit = ISCommit && ISIMG; if (isCommit) {frm.Action = "Sobre: Blank"; frm.submit (); }} / *** ErrorImg Erro de imagem Exibição* @Params IMG Image Object* @return void ** / function ErrorImg (img) {img.src = nofoto; } </script> </adhead> <body> <names name = "frm" method = "post"> <p id = "errortips"> </p> <tabela CellPadding = "1" CellPacing = "0"> <tr> <td> <bel> name: </etc. </tr> <tr> <td> <brety> gênero: </elabel> </td> <td> <typ type = "radio" name = "sexo" value = "0"/> masculino <input type = "radio" name = "sexo" email = "0"/> fêmea </td </tr> <tr> <td> <bel "email =" 0 "/> name = "email" maxlength = "100"/> </td> </tr> <tr> <td> <lable> imagem </elabel> </td> <td> <td> <tabela celularpadding = "0" CellPacing = "0"> <Tr> <td> <mg src = "imgs/notoo.g" Oneerror = "JavaScript: ErrorImg (this);" ONREADESTATECHANGE = "JavaScript: Sizecheck (this);"/> </td> </tr> <tr> <td> <input type = "file" name = "uploadimg" onchange = "javaScript: checkFileChange (this);" size = "12"/> </td> </tr> </tabela> </td> </tr> <tr> <td colspan = "2"> <a href = "javascript: commit ();" rel = "Nofollow externo" rel = "Nofollow externo" href = "javascript: commit ();" rel = "Nofollow externo" rel = "Nofollow externo"> registro </a> </td> </tr> </tabela> </form> </body> </html>