SpringMVC 上传图片保存到服务器 同时更改图片名称保存至数据库

@RequestMapping("upload")
public void upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request,HttpServletResponse response, ModelMap model){
System.out.println("开始");
// String filepath=OtoPropertites.get("filepatch");
String path = request.getSession().getServletContext().getRealPath("/upload");//图片上传路径

String fileName = file.getOriginalFilename();
String sname = fileName.substring(fileName.lastIndexOf("."));
String uuid = UUID.randomUUID().toString();
String kzS=".jpg";//图片后缀名
if(sname.equals("")){
kzS=sname;
}
String newfileName = uuid+sname;
System.out.println(path);
File targetFile = new File(path, newfileName);
if(!targetFile.exists()){
targetFile.mkdirs();
}
try {
file.transferTo(targetFile); //保存
} catch (Exception e) {
e.printStackTrace();
}
String fileUrl= request.getContextPath()+"/upload/"+newfileName;
System.out.print(request.getContextPath());
Map m=new HashMap();
m.put("d", fileUrl);//图片路径
System.out.println();
if(!sname.equals(".PNG")&&!sname.equals(".png")){
ImageUtils.scaleWithWidth(path+"/"+newfileName,600,false);
}

this.responseMsg(response, Object2Json.bean2Json2(m));//转JSON 返回到前台

}

/**
* 按宽度值等比例缩放
* @param srcImageFile
* @param scale
* @param flag
*/
public final static void scaleWithWidth(String srcImageFile,
int tmpwidth, boolean flag) {
try {
BufferedImage src = ImageIO.read(new File(srcImageFile)); // 读入文件
int width = src.getWidth(); // 得到源图宽
int height = src.getHeight(); // 得到源图长
float scale =width/tmpwidth;
int ewidth=width;
int eheight=height;
if (flag) {// 放大
ewidth = (int)(width * scale);
eheight =(int)(height * scale);
} else {// 缩小
if(width>tmpwidth){
ewidth = (int)(width / scale);
eheight = (int)(height / scale);
}
}
Image image = src.getScaledInstance(ewidth, eheight,
Image.SCALE_DEFAULT);
BufferedImage tag = new BufferedImage(ewidth, eheight,
BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(image, 0, 0, null); // 绘制缩小后的图
g.dispose();
ImageIO.write(tag, "JPEG", new File(srcImageFile));// 输出到文件流
} catch (IOException e) {
e.printStackTrace();
}
}

转载于:https://www.cnblogs.com/hqhouse/p/5260717.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值