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

springmvc处理上传图片代码(校验图片尺寸、图片大小)的更多相关文章

  1. PHP高效获取远程图片尺寸和大小(转)

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 3 ...

  2. PHP高效获取远程图片尺寸和大小

    /** * 获取远程图片的宽高和体积大小 * * @param string $url 远程图片的链接 * @param string $type 获取远程图片资源的方式, 默认为 curl 可选 f ...

  3. dnmp(docker的lnmp)安装WordPress之后图片上传问题 问题:图片上传大小问题解决和 报错413 Request Entity Too Large

    首先是提示超过图片尺寸和大小, 最后发现都是图片大小的问题, 需要修改php的最大上传size 修改之后查看php配置  已经生效  但是还是报错, 提示返回不是合法的json,  查看控制台, 报错 ...

  4. 基于html5 canvas 的客户端异步上传图片的插件,支持客户端压缩图片尺寸

    /** * Created by xx on 15-05-28. * 基于html5 canvas 的客户端异步上传画片的插件 * 在实际应用中,常常要用于上传图片的功能.在现在越来越多的手机weba ...

  5. 将“Cocos2dx-截屏并设置图片尺寸 ”中cocos2d-x代码转换为2.2的代码

    Cocos2dx-截屏并设置图片尺寸: http://www.cocos2dev.com/?p=522 2.2 代码如下: void HelloWorld::screenShoot() { CCSiz ...

  6. 图片尺寸批量resize的matlab并行代码

    在caffe ImageNet例子中有对图片进行resize的部分,文中使用的是linux shell脚本命令: for name in /path/to/imagenet/val/*.JPEG; d ...

  7. 通过input上传图片,判断不同浏览器及图片类型和大小的js代码

    1.jsp页面代码 <form id="userPhoto" name="userPhoto" method="post" actio ...

  8. C#上传图片和生成缩略图以及图片预览

    因工作需要,上传图片要增加MIME类型验证和生成较小尺寸的图片用于浏览.根据网上代码加以修改做出如下效果图: 前台代码如下: <html xmlns="http://www.w3.or ...

  9. angular-file-upload封装为指令+图片尺寸限制

    不了解angular-file-upload基础使用 请先参考http://blog.csdn.net/lai_xu/article/details/49535847 博客地址 下文如果有更好的建议请 ...

随机推荐

  1. C语言的傻瓜式随笔(一):嵌套循环-程序结构

    循环语句的嵌套 一个循环结构内可以含有另一个循环,称为循环嵌套,又称多重循环.常用的循环嵌套是二重循环,外层循环称为外循环,内层循环称为内循环. ---------不知道哪来的基础概念 这是本宝宝的第 ...

  2. 【五】将博客从jekyll迁移到了hexo

    本系列有五篇:分别是  [一]Ubuntu14.04+Jekyll+Github Pages搭建静态博客:主要是安装方面  [二]jekyll 的使用 :主要是jekyll的配置  [三]Markdo ...

  3. 安装ant

    从ant官方网站下载ant安装包:apache-ant-1.9.7-bin.tar.gz,解压 tar xvf apache-ant-1.9.7-bin.tar.gz -C /usr/java/ 配置 ...

  4. [Unity][Heap sort]用Unity动态演示堆排序的过程(How Heap Sort Works)

    [Unity][Heap sort]用Unity动态演示堆排序的过程 How Heap Sort Works 最近做了一个用Unity3D动态演示堆排序过程的程序. I've made this ap ...

  5. Azure Table storage 基本用法 -- Azure Storage 之 Table

    Azure Storage 是微软 Azure 云提供的云端存储解决方案,当前支持的存储类型有 Blob.Queue.File 和 Table,其中的 Table 就是本文的主角 Azure Tabl ...

  6. Azure SQL Database (19) Stretch Database 概览

    <Windows Azure Platform 系列文章目录>  Azure SQL Database (19) Stretch Database 概览      Azure SQL Da ...

  7. TODO:MongoDB MySQL数据库备份

    TODO:MongoDB MySQL数据库备份 1. MongoDB使用命令备份 mongodump进行整个数据库备份,主要用到的命令参数: -d 要备份的数据库 -o 输出的路径 ./mongodu ...

  8. Java异常内容总结

    在程序开发中,可能存在各种错误,有些错误是可以避免的,而有些错误却是意想不到的,在Java中把这些可能发生的错误称为异常. Throwable类是所有异常类的超类,该类的两个直接子类是Error和Ex ...

  9. titit. 深入理解 内聚( Cohesion)原理and  attilax大总结

    atitit. 深入理解 内聚( Cohesion)原理and  attilax大总结         1.1. 内聚的概念 1 1.1.1. 高内聚模式关于这个问题给出的答案是:分配职责,使其可保持 ...

  10. EF Power Tools参数不正确的解决方法

    在Visual Studio 2010安装了EF Power Tools Beta 3之后,希望根据本地现有数据库模型来生成基于Entity Framework Code First的代码时,经常出现 ...