springmvc上传图片
/**
* 图片尺寸为 1:1,大小<1M
* @param response
* @param out
* @param file
*/
@RequestMapping("/savePic")
@ResponseBody
public void savePic(HttpServletResponse response,PrintWriter out,MultipartFile file){
{
HashMap<String, Object> map = new HashMap<>();
BufferedImage src = null;
try {
src = ImageIO.read(file.getInputStream());
int fh = src.getHeight();
int fw = src.getWidth();
long fileSize = file.getSize();
if(fileSize<=(1024*1024)&&fh==fw){
map = FileUploadUtil.saveImage(file, response);
map.put("code", 1);
}else if(fileSize>(1024*1024)){
map.put("code", 2);
map.put("msg", "图片最大只能为1M");
}else if(fh!=fw){
map.put("code", 2);
map.put("msg", "图片尺寸必须为1:1");
} else{
map.put("code", 3);
map.put("msg", "图片上传异常");
}
out.println(JsonUtil.jsonObject(map, new String[]{}, null));
} catch (Exception e) {
logger.error(e);
map.put("code", 4);
map.put("msg", "数据异常");
out.println(JsonUtil.jsonObject(map, new String[]{}, null));
}
}
public static HashMap<String, Object> saveImage(MultipartFile file,HttpServletResponse response){
String picname = System.currentTimeMillis()+"";
HashMap<String, Object> map = new HashMap<>();
String fullpicname = "";
String savepath = ParametersUtil.readFile();
File fileDir = new File(savepath);
if(!fileDir.exists()){
fileDir.mkdirs();
}
try {
String ofn = file.getOriginalFilename();
String extensionName = ofn.substring(ofn.lastIndexOf(".")+1);
fullpicname = picname+"."+extensionName;
FileOutputStream fileout = new FileOutputStream(savepath+"/"+fullpicname);
fileout.write(file.getBytes());
map.put("url",ContentUtil.TESTPICURL+"/"+fullpicname);
fileout.flush();
fileout.close();
return map;
} catch (Exception e) {
}
return null;
}