上传图片
前端代码:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>单图片上传</title> </head> <body> <div style="color: red"> <c:forEach items="${errs}" var="err"> <div>${err}</div> </c:forEach> </div> <fieldset> <legend>图片上传</legend> <h2>只能上传单张10M以下的 PNG、JPG、GIF 格式的图片</h2> <form action="/shop/shop1" method="post" enctype="multipart/form-data"> 选择文件:<input type="file" name="ufile"> <input type="submit" value="上传"> </form> </fieldset> </body> </html>
后台代码:
@Controller @RequestMapping("/shop") public class ImgController { @RequestMapping(method = RequestMethod.GET) public String img() { return "img"; } @PostMapping("/shop1") public String img(@RequestPart("ufile") MultipartFile file, Model model, HttpServletRequest req) { if (file.isEmpty()) { model.addAttribute("err", "不能为空"); return "img"; } //图片验证 if (!file.getContentType().contains("image/")) { model.addAttribute("err", "只允许图片上传"); return "img"; } //图片大小只能为5M if (file.getSize() > 1024 * 1024 * 5) { model.addAttribute("err", "文件超出大小"); return "img"; } //路径 String path = req.getServletContext().getRealPath(""); path = path + "images\\"; File file1 = new File(path); if (!file1.exists()) { //如果不存在就创建 file1.mkdirs(); } String filename = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf(".")); filename = "upload_" + filename + "_" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()); filename = filename + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."), file.getOriginalFilename().length()); try { file.transferTo(new File(path + "\\" + filename)); } catch (IOException e) { model.addAttribute("err", "文件上传失败,请重新上传"); } return "img"; }