java 上传图片内容校验_springmvc处理上传图片代码(校验图片尺寸、图片大小)

packagecom.maizuo.web.controller;importcom.maizuo.domain.Result;importcom.maizuo.util.ConstantsConfig;importcom.maizuo.util.Upload;importhyxlog.Log;importnet.sf.json.JSONObject;importorg.apache.commons.lang.StringUtils;importorg.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.*;importorg.springframework.web.multipart.MultipartFile;importjavax.imageio.ImageIO;importjavax.servlet.http.HttpServletRequest;importjava.awt.image.BufferedImage;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileNotFoundException;importjava.io.IOException;importjava.util.Date;importjava.util.List;/*** Created by qiyang on 2015/6/15 and improved by heisenberg on 2016/04/18*/@Controller

@RequestMapping("/api/upload")public classUploadController {

@RequestMapping(value= "/img", method =RequestMethod.POST)

@ResponseBodypublic Result uploadImg(@RequestParam(value = "file", required = false) MultipartFile file, String pathName,

Integer sizeRule, Integer isDeviation, HttpServletRequest request)throwsFileNotFoundException, IOException {

String loghead= "通用接口-上传图片:";

JSONObject json= newJSONObject();if (file == null) {

Log.info(loghead+ "上传失败:文件为空");return new Result(900001, "", "上传失败:文件为空");

}if(StringUtils.isBlank(pathName)) {

pathName= ConstantsConfig.getString("DEFALTUPLOADPATH");

}

List 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= newFile(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= newDate();

String tmpFileName= String.valueOf(now.getTime()) + Math.round(Math.random() * 1000) + "." +fileExt;//文件保存路径

String tmpFilePath = uploadPath +tmpFileName;

tmpFile= newFile(tmpFilePath);

file.transferTo(tmpFile);

BufferedImage sourceImg= ImageIO.read(newFileInputStream(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, "后台校验上传图片流程异常");

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是SpringMVC文件上及查看的示例代码: 1. 文件上: ```java @Controller @RequestMapping("/file") public class FileController { @RequestMapping(value = "/upload", method = RequestMethod.POST) @ResponseBody public String upload(@RequestParam("file") MultipartFile file) { try { // 保存文件 String fileName = file.getOriginalFilename(); String filePath = "/path/to/save/" + fileName; File dest = new File(filePath); file.transferTo(dest); return "success"; } catch (Exception e) { e.printStackTrace(); return "error"; } } } ``` 2. 文件查看: ```java @Controller @RequestMapping("/file") public class FileController { @RequestMapping("/list") public String list(Model model) { // 获取文件列表 String fileDirPath = "/path/to/list/"; File fileDir = new File(fileDirPath); File[] fileList = fileDir.listFiles(); List<String> fileNameList = new ArrayList<>(); for (File file : fileList) { fileNameList.add(file.getName()); } model.addAttribute("fileNameList", fileNameList); return "file/list"; } @RequestMapping("/download/{fileName}") public void download(@PathVariable("fileName") String fileName, HttpServletResponse response) { // 下载文件 String filePath = "/path/to/download/" + fileName; try { FileInputStream fis = new FileInputStream(filePath); response.setContentType("application/force-download"); response.addHeader("Content-Disposition", "attachment;fileName=" + fileName); byte[] buffer = new byte[1024]; int len; while ((len = fis.read(buffer)) != -1) { response.getOutputStream().write(buffer, 0, len); } fis.close(); } catch (Exception e) { e.printStackTrace(); } } } ``` 其中,list方法用于获取文件列表,download方法用于下载文件。注意,download方法中设置了响应头,告诉浏览器下载的文件名字,并将文件内容写入响应体。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值