300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > SpringMVC 上传图片保存到服务器 同时更改图片名称保存至数据库

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

时间:2023-02-19 00:28:17

相关推荐

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();

}

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。