zoukankan      html  css  js  c++  java
  • springmvc处理上传图片代码(校验图片尺寸、图片大小)

    package com.maizuo.web.controller;
    
    import com.maizuo.domain.Result;
    import com.maizuo.util.ConstantsConfig;
    import com.maizuo.util.Upload;
    import hyxlog.Log;
    import net.sf.json.JSONObject;
    import org.apache.commons.lang.StringUtils;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.*;
    import org.springframework.web.multipart.MultipartFile;
    import javax.imageio.ImageIO;
    import javax.servlet.http.HttpServletRequest;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.util.Date;
    import java.util.List;
    
    /**
     * Created by qiyang on 2015/6/15 and improved by heisenberg on 2016/04/18
     */
    @Controller
    @RequestMapping("/api/upload")
    public class UploadController {
        @RequestMapping(value = "/img", method = RequestMethod.POST)
        @ResponseBody
        public Result uploadImg(@RequestParam(value = "file", required = false) MultipartFile file, String pathName,
                Integer sizeRule, Integer isDeviation, HttpServletRequest request)
                        throws FileNotFoundException, IOException {
            String loghead = "通用接口-上传图片:";
    
            JSONObject json = new JSONObject();
            if (file == null) {
                Log.info(loghead + "上传失败:文件为空");
                return new Result(900001, "", "上传失败:文件为空");
            }
            if (StringUtils.isBlank(pathName)) {
                pathName = ConstantsConfig.getString("DEFALTUPLOADPATH");
            }
            List<Object> uploadPathNames = ConstantsConfig.getList("UPLOADPATHNAMES");
            boolean flag = false;
            for (int i = 0; i < uploadPathNames.size(); i++) {
                if (pathName.equals(uploadPathNames.get(i))) {
                    flag = true;
                }
            }
            if (!flag) {
                Log.info(loghead + "上传失败:上传路径无效");
                return new Result(900001, "", "上传失败:上传路径无效");
            }
            String fileName = file.getOriginalFilename();
            // 获取上传文件扩展名
            String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
            // 对扩展名进行小写转换
            fileExt = fileExt.toLowerCase();
            // 图片文件大小过滤
            if (!"jpg".equals(fileExt) && !"jpeg".equals(fileExt) && !"png".equals(fileExt) && !"bmp".equals(fileExt)
                    && !"gif".equals(fileExt)) {
                Log.info(loghead + "上传失败:无效图片文件类型");
                return new Result(900001, "", "上传失败:无效图片文件类型");
            }
            long fileSize = file.getSize();
            Log.info(loghead + "fileInfo:fileName=" + fileName + "&fileSize=" + fileSize);
            if (fileSize <= 0) {
                Log.info(loghead + "上传失败:文件为空");
                return new Result(900001, "", "上传失败:文件为空");
            } else if (fileSize > (500 * 1024)) {
                Log.info(loghead + "上传失败:文件大小不能超过500K");
                return new Result(900001, "", "上传失败:文件大小不能超过500K");
            }
            File tmpFile = null;
            // 判断文件是否为空
            if (!file.isEmpty()) {
                String uploadPath = request.getSession().getServletContext().getRealPath("/") + "/upload/";
                File uploadDir = new File(uploadPath);
                if (uploadDir.exists() && uploadDir.isDirectory()) {
                    String[] childFileNameList = uploadDir.list();
                    if (childFileNameList != null) {
                        File temp;
                        for (int i = 0; i < childFileNameList.length; i++) {
                            temp = new File(uploadPath + childFileNameList[i]);
                            if (temp.isFile()) {
                                temp.delete();
                            }
                        }
                    }
                } else {
                    uploadDir.mkdir();
                }
    
                try {
                    Date now = new Date();
                    String tmpFileName = String.valueOf(now.getTime()) + Math.round(Math.random() * 1000) + "." + fileExt;
                    // 文件保存路径
                    String tmpFilePath = uploadPath + tmpFileName;
                    tmpFile = new File(tmpFilePath);
                    file.transferTo(tmpFile);
                    BufferedImage sourceImg = ImageIO.read(new FileInputStream(tmpFile));
                    int imgWidth = sourceImg.getWidth();
                    int imgHeight = sourceImg.getHeight();
                    System.out.println("上传的图片宽:" + imgWidth);
                    System.out.println("上传的图片高:" + imgHeight);
                    // 图片文件尺寸过滤
                    if (sizeRule == null) {
                        // 上传到图片服务器
                        String imgUrl = Upload.upload(tmpFile, "/" + pathName + "/");
                        json.put("fileName", fileName);
                        json.put("url", imgUrl);
                        json.put("imgWidth", imgWidth);
                        json.put("imgHeight", imgHeight);
                        return new Result(0, json, "success");
                    } else {
                        System.out.println("前端选择图片尺寸规则" + sizeRule);
                        int ruleWidth = 0;
                        int ruleHeight = 0;
                        try {
                            String imgSizeRule = ConstantsConfig.getString("UPLOADIMG_RULE" + sizeRule);
                            String imgSizeRule_width_height[] = imgSizeRule.split(",");
                            String imgSizeRule_width = imgSizeRule_width_height[0];
                            String imgSizeRule_height = imgSizeRule_width_height[1];
                            ruleWidth = Integer.parseInt(imgSizeRule_width);
                            ruleHeight = Integer.parseInt(imgSizeRule_height);
                        } catch (Exception e) {
                            System.out.println("没有配置尺寸规则" + sizeRule);
                            json.put("fileName", fileName);
                            json.put("imgWidth", imgWidth);
                            json.put("imgHeight", imgHeight);
                            return new Result(-1, json, "配置系统没有配置上传图片尺寸规则" + sizeRule
                                    + ",请前端修改参数sizeRule值或管理员在配置系统配置sizeRule" + sizeRule + "规则对应的配置项");
                        }
                        if (isDeviation == null) {
                            System.out.println("严格限制图片尺寸");
                            if (ruleWidth == imgWidth && ruleHeight == imgHeight) {
                                String imgUrl = Upload.upload(tmpFile, "/" + pathName + "/");
                                json.put("fileName", fileName);
                                json.put("url", imgUrl);
                                json.put("imgWidth", imgWidth);
                                json.put("imgHeight", imgHeight);
                                return new Result(0, json, "success");
                            } else {
                                json.put("fileName", fileName);
                                json.put("imgWidth", imgWidth);
                                json.put("imgHeight", imgHeight);
                                json.put("ruleWidth", ruleWidth);
                                json.put("ruleHeight", ruleHeight);
                                return new Result(-1, json, "请上传" + ruleWidth + "*" + ruleHeight + "px的图片");
                            }
                        } else {
                            int deviation = Integer.parseInt(ConstantsConfig.getString("UPLOADIMG_DEVIATION"));
                            System.out.println("允许尺寸误差在" + deviation + "以内");
                            if (Math.abs(ruleWidth - imgWidth) <= deviation
                                    && Math.abs(ruleHeight - imgHeight) <= deviation) {
                                String imgUrl = Upload.upload(tmpFile, "/" + pathName + "/");
                                json.put("fileName", fileName);
                                json.put("url", imgUrl);
                                json.put("imgWidth", imgWidth);
                                json.put("imgHeight", imgHeight);
                                return new Result(0, json, "success");
                            } else {
                                json.put("fileName", fileName);
                                json.put("imgWidth", imgWidth);
                                json.put("imgHeight", imgHeight);
                                json.put("ruleWidth", ruleWidth);
                                json.put("ruleHeight", ruleHeight);
                                return new Result(-1, json, "请上传" + ruleWidth + "*" + ruleHeight + "px的图片");
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.info(loghead + "上传失败:文件上传失败");
                    return new Result(900001, "", "上传失败:文件上传异常");
                } finally {
                    // 删除临时文件
                    if (tmpFile.exists()) {
                        tmpFile.deleteOnExit();
                        Log.info(loghead + "删除临时文件" + tmpFile.getAbsolutePath());
                    }
                }
            }
            return new Result(-1, json, "后台校验上传图片流程异常");
        }
    }

    本文转自:koushr

  • 相关阅读:
    关于思考力
    2019第24周日
    提高收入的方法
    工作中的管理
    技术是解决问题的一种手段
    Django的事务性
    shell单引号与变量、双引号与变量、如何在多重引号里面取到shell变量的值?
    django外键以及主表和子表的相互查询
    django数据模型中 null=True 和 blank=True 有什么区别?
    Django静态文件的加载以及STATIC_URL、 STATIC_ROOT 、STATICFILES_DIRS的区别
  • 原文地址:https://www.cnblogs.com/wkrbky/p/6243318.html
Copyright © 2011-2022 走看看