1.
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 7 <script type="text/javascript"> 8 var imgPath; 9 var image; 10 var acceptExt = ["gif", "jpg", "bmp", "png"]; //允许后缀名 11 var widthLimit = {"min" : 0, "max" : 2000}; //宽度限制 12 var heightLimit = {"min" : 0, "max" : 2000}; //高度限制 13 14 /* 预览图片 */ 15 function preview(){ 16 document.getElementById('preview').style.display = 'none'; 17 document.getElementById('box').innerHTML = "<img width='" + image.width + "' height='" + image.height + "' src='" + imgPath + "'>"; 18 } 19 20 /* 检测图片大小 */ 21 function checkSize() { 22 if ( image.width == 0 || image.height == 0 ) { 23 setTimeout(checkSize, 200); 24 } else { 25 if(image.width < widthLimit.min || image.width >= widthLimit.max || image.height < heightLimit.min || image.height >= heightLimit){ 26 alert("文件大小不符合要求"); 27 } else { 28 document.getElementById('preview').style.display = 'block'; 29 } 30 } 31 } 32 33 /* 加载图片 */ 34 function loadImage(file) { 35 //检查图片 36 if(checkExt(file)){ 37 //获取图片路径 38 imgPath = getPath(file); 39 image = new Image(); 40 image.src = imgPath; 41 setTimeout(checkSize, 200); 42 } 43 } 44 45 /* 获取图片路径 */ 46 function getPath(file){ 47 if(file){ 48 //window.navigator.userAgent属性包含了浏览器类型、版本、操作系统类型、浏览器引擎类型等信息, 49 //通过这个属性来判断浏览器类型,下面是我写的一个函数,这个函数返回一个包含浏览器名称和版本的数组。 50 //此函数可区分ie5.5~ie11、Chrome、Opera、Safair、Firefox这5种常见浏览器。 51 if (window.navigator.userAgent.toLowerCase().indexOf("msie")>=1){ 52 file.select(); 53 // IE下取得图片的本地路径 54 return document.selection.createRange().text; 55 } else if (window.navigator.userAgent.toLowerCase().indexOf("firefox")>=1){ 56 //firefox 57 if(file.files){ 58 // Firefox下取得的是图片的数据 59 return file.files.item(0).getAsDataURL(); 60 } 61 } 62 return file.value; 63 } 64 } 65 66 /* 检测后缀名 */ 67 function checkExt(file) { 68 if(!file.value){ 69 alert("请选择要上传的图片!"); 70 return false; 71 } else if(!!this.acceptExt.length && !RegExp("\.(" + acceptExt.join("|") + ")$", "i").test(file.value)){ 72 alert("图片格式错误!"); 73 return false; 74 } 75 76 return true; 77 } 78 </script> 79 </head> 80 81 <body> 82 <input type="file" name="pic" id="pic" onchange='loadImage(this)' /> 83 <input id='preview' type='button' value='preview' style='display:none;' onclick='preview();'> 84 <div id='box'></div> 85 </body> 86 </html>
浙公网安备 33010602011771号