做图片上传功能时,我们经常会遇到一个问题就是,就是要对上传的图片进行一个校验,校验的东西包括图片的大小、尺寸(即宽和高)以及图片的类型。
今天我主要介绍两种方式来进行图片的校验,一种是在前端用js校验,另一种是放在服务器端校验。接下来我们来进行介绍
下面直接贴源代码,注释也写在代码里面
1 <%@ page language="java" contenttype="text/html; charset=UTF-8" pageencoding="UTF-8"%> 2 <%@ include file="../common/common_tags.jsp" %> 3 <!DOCTYPE html> 4 <html lang="en"> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> 7 <title>素材列表>图片编辑</title> 8 </head> 9 <body> 10 <form action="${path}/materialImage/update.do" method="post"> 11 <input type="file" id="sdfile" name="sdfile" onchange="preImg(this.id,‘preview_2‘);"> 12 </form> 13 <div id="tip1"> 14 </div> 15 <div id="tip2"> 16 </div> 17 <script> 18 /**图片的大小要求,不超过80KB,单位是KB*/ 19 var size = "80"; 20 /**图片的类型要求(即文件后缀)*/ 21 var suffix = "jpg,png"; 22 /**图片宽高要求,单位是px*/ 23 var width = "640"; 24 var height = "530"; 25 var suffixList =""; 26 function preImg(fileid, previewid) 27 { 28 var name = document.getElementById(fileid).files[0].name; 29 var curSize = document.getElementById(fileid).files[0].size; 30 var curSuffix = name.split(".")[1]; 31 console.info(document.getElementById(fileid).files[0]) 32 //1、判断图片大小 33 if(curSize>size*1024) 34 { 35 alert("图片大小不能超过"+size+"KB!"); 36 return; 37 } 38 //2、判断图片类型 39 if(suffix.indexOf(curSuffix)==-1) 40 { 41 suffixList="图片只能以"; 42 for(var j=0;j<suffix.split(",").length;j++) 43 { 44 if(j==0) 45 { 46 suffixList+="."+suffix.split(",")[j]; 47 } 48 else 49 { 50 suffixList+="或."+suffix.split(",")[j]; 51 } 52 } 53 suffixList+="结尾!" 54 alert(suffixList+""); 55 return; 56 } 57 /* 58 3、 判断图片的尺寸(即宽和高) 59 现在的问题是,如何读取图片的宽、高 60 我这里是通过实例化Image对象、加载src 来获取。 61 */ 62 var reader = new FileReader(); 63 var picpreview = document.getElementById(previewid); 64 reader.onload = function(e) { 65 var data = e.target.result; 66 //加载图片获取图片真实宽度和高度 67 var image = new Image(); 68 image.onload=function(){ 69 var w = image.width; 70 var h = image.height; 71 if(w!=width || h!=height) 72 { 73 alert("请上传尺寸为尺寸为"+width+"x"+height"的图片,当前图片尺寸为"+w+"x"+h+"!"); 74 return; 75 } 76 } 77 image.src= data; 78 picpreview.innerHTML = "<img src=‘"+this.result+"‘ class=‘‘ style=‘height: 282px;‘ />"; 79 } 80 reader.readAsDataURL(document.getElementById(fileid).files[0]); 81 } 82 </script>
第二种:放到服务器端校验
首先看用到jsp页面是如下
1 <%@ page language="java" contenttype="text/html; charset=UTF-8" pageencoding="UTF-8"%> 2 <%@ include file="../common/common_tags.jsp" %> 3 <!DOCTYPE html> 4 <html lang="en"> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> 7 <title>素材列表>图片编辑</title> 8 </head> 9 <body> 10 <form action="${path}/materialImage/update.do" method="post"> 11 <input type="file" id="sdfile" name="sdfile" onchange="preImg(this.id ,‘preview_2‘);"> 12 </form> 13 <div id="tip1"> 14 </div> 15 <div id="tip2"> 16 </div> 17 <script> 18 function preImg(fileid, previewid) 19 { 20 //异步校验图片格式 21 $.ajax({ 22 type: "POST", 23 url: "${path}/materialImage/imageCheck.do", 24 data: formdata, 25 contentType: false, 26 processData: false, 27 async: false, 28 cache: false, 29 success: function(data) { 30 if (data.result == 0) { 31 alert("请上传图片JPG或GIF格式的图片!!"); 32 errorCount++; 33 } else if (data.result == 1) { 34 alert("请上传图片格式等于" + imgWidth + "×" + imgHeight + " 格式的图片!!"); 35 } else if (data.result == 2) { 36 imgSize = data.imageSize; 37 alert("图片大于" + data.imageSize + "K!"); 38 } 39 } 40 } 41 </script>
再看服务器端代码
1 package com.lutongnet.cps.material.controller; 2 3 import java.awt.image.BufferedImage; 4 import java.io.File; 5 import java.io.IOException; 6 import java.util.ArrayList; 7 import java.util.Date; 8 import java.util.HashMap; 9 import java.util.Iterator; 10 import java.util.List; 11 import java.util.Map; 12 13 import javax.annotation.Resource; 14 import javax.imageio.ImageIO; 15 import javax.imageio.ImageReader; 16 import javax.imageio.stream.ImageInputStream; 17 import javax.servlet.http.HttpServletRequest; 18 19 import org.apache.commons.fileupload.disk.DiskFileItem; 20 import org.slf4j.Logger; 21 import org.slf4j.LoggerFactory; 22 import org.springframework.http.HttpHeaders; 23 import org.springframework.stereotype.Controller; 24 import org.springframework.ui.Model; 25 import org.springframework.web.bind.annotation.ModelAttribute; 26 import org.springframework.web.bind.annotation.RequestMapping; 27 import org.springframework.web.bind.annotation.RequestParam; 28 import org.springframework.web.bind.annotation.ResponseBody; 29 import org.springframework.web.multipart.MultipartHttpServletRequest; 30 import org.springframework.web.multipart.commons.CommonsMultipartFile; 31 32 33 /** 34 * 图片素材Controller 35 * @author hehaitao 36 * @since 1.0 37 */ 38 @Controller 39 @RequestMapping(value = "/materialImage") 40 public class MaterialImageController2 41 { 42 private static Logger log = LoggerFactory.getLogger(MaterialImageController2.class); 43 44 @RequestMapping(value = "/imageCheck") 45 @ResponseBody 46 public Map<String,Object> imageCheck(HttpServletRequest request) 47 throws IOException 48 { 49 Map<String, Object> jsonMap = new HashMap<String, Object>(); 50 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; 51 CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file"); 52 DiskFileItem fi = (DiskFileItem)file.getFileItem(); 53 File bigFile = fi.getStoreLocation(); 54 55 //判断图片格式必须为JPEG才开始上传 56 if(checkImageType(bigFile, "JPEG") && (checkImageType(bigFile, "gif")) ) 57 { 58 log.error("image type error!"); 59 jsonMap.put("result", 0); 60 } 61 62 if(checkImageElement(bigFile, 1280, 720)) 63 { 64 log.error("image element error!"); 65 jsonMap.put("result", 1); 66 } 67 if(checkImageSize(bigFile, 400) && checkImageType(bigFile, "gif")) 68 { 69 log.error("image size too large!"); 70 jsonMap.put("imageName","上传的高清gif"); 71 jsonMap.put("imageSize",400); 72 jsonMap.put("result", 2); 73 } 74 if(checkImageSize(bigFile, 100) && checkImageType(bigFile, "JPEG")) 75 { 76 log.error("image size too large!"); 77 jsonMap.put("imageName","上传的高清jpg"); 78 jsonMap.put("imageSize",100); 79 jsonMap.put("result", 3); 80 } 81 82 return jsonMap; 83 } 84 85 /** 86 * 图片后缀的格式检验 87 * @param file 文件 88 * @param imageType 后缀格式,如"JPEG,png.." 89 * @return true:符合imageType格式; false:不符合 90 * @throws IOException 91 */ 92 public static boolean checkImageType(File file, String imageType) throws IOException 93 { 94 if(!file.exists()) 95 { 96 return false; 97 } 98 boolean result = false; 99 ImageInputStream iis = ImageIO.createImageInputStream(file); 100 Iterator<ImageReader> readers = ImageIO.getImageReaders(iis); 101 ImageReader reader = null; 102 if(readers.hasNext()) 103 { 104 reader = readers.next(); 105 } 106 if(reader.getFormatName().equals(imageType)) 107 { 108 result = true; 109 } 110 //System.out.println(reader.getFormatName()); 111 return result; 112 } 113 114 /** 115 * 图片的像素判断 116 * @param file 文件 117 * @param imageWidth 图片宽度 118 * @param imageHeight 图片高度 119 * @return true:上传图片宽度和高度都小于等于规定最大值 120 * @throws IOException 121 */ 122 public static boolean checkImageElement(File file, int imageWidth, int imageHeight) throws IOException 123 { 124 boolean result = false; 125 if(!file.exists()) 126 { 127 return false; 128 } 129 BufferedImage bufferedImage = ImageIO.read(file); 130 if(bufferedImage != null && bufferedImage.getHeight() == imageHeight && bufferedImage.getWidth() == imageWidth) 131 { 132 result = true; 133 } 134 return result; 135 } 136 137 /** 138 * 检测图片的大小 139 * @param file 文件 140 * @param imageSize 图片最大值(KB) 141 * @return true:上传图片小于图片的最大值 142 */ 143 public static boolean checkImageSize(File file, int imageSize) 144 { 145 boolean result = false; 146 if(!file.exists()) 147 { 148 return false; 149 } 150 if((file.length() / 1024) <= imageSize) 151 { 152 result = true; 153 } 154 155 return result; 156 } 157 158 159 160 }
原文:http://www.cnblogs.com/zishengY/p/7241051.html