springmvc处理上传图片代码(校验图片尺寸、图片大小)

这是一个关于SpringMVC控制器处理图片上传的代码示例,包括校验图片尺寸和大小。通过MultipartFile接收文件,检查文件类型、大小,并根据预设规则验证图片尺寸,最后将图片上传至服务器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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, "后台校验上传图片流程异常");
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值