做圖片上傳功能時,我們經常會遇到一個問題就是,就是要對上傳的圖片進行一個校驗,校驗的東西包括圖片的大小、尺寸(即寬和高)以及圖片的類型。
今天我主要介紹兩種方式來進行圖片的校驗,一種是在前端用js校驗,另一種是放在服務器端校驗。接下來我們來進行介紹
第一種:放在前端用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 }