您的位置:首页 > 其它

检验上传图片大小、尺寸、类型的两种实现方案

2017-07-26 22:01 465 查看
做图片上传功能时,我们经常会遇到一个问题就是,就是要对上传的图片进行一个校验,校验的东西包括图片的大小、尺寸(即宽和高)以及图片的类型。

今天我主要介绍两种方式来进行图片的校验,一种是在前端用js校验,另一种是放在服务器端校验。接下来我们来进行介绍

第一种:放在前端用js校验

下面直接贴源代码,注释也写在代码里面

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 }


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: