SpringBoot 2.0
1.upLoad.html
1 <!DOCTYPE html>
2 <html lang="en" xmlns:th="http://www.thymeleaf.org">
3 <head>
4 <meta charset="UTF-8">
5 <title>Upload Page</title>
6 </head>
7
8 <body>
9 <form action="/index.do/upload" method="post" enctype="multipart/form-data">
10 <table>
11 <tr>
12 <td><input type="file" id="fileNameEmg" name="fileNameEmg"></td><h2 th:text="${emg}"/>
13 <td th:if="${emg=='上传成功!'}"><img th:src="@{'/img/'+${image}}" alt="picture" width="100px" height="100px" /></td>
14 </tr>
15 <tr>
16 <td><input type="button" value="submit" onclick="aa(this)"></td>
17 </tr>
18 </table>
19
20 </form>
21 <script>
22
23 function aa(obj){
24 var fiel = document.getElementById("fileNameEmg");
25 var a = fiel.value;
26 if(a.indexOf(".png")!=-1||a.indexOf(".jpg")!=-1){
27
28 obj.form.submit()
29 }else{
30 alert("请选择图片文件")
31 }
32 }
33 </script>
34 </body>
35 </html>
2.uploadController.java
1 @Controller
2 @RequestMapping("index.do")
3 public class userController {
4
5 @RequestMapping("/uploadEng")
6 public String up(@RequestParam("fileNameEmg") MultipartFile file,Model model) throws Exception{
7
8 if (file.isEmpty()){
9 System.out.println("--=========");
10 model.addAttribute("emg","请选择要上传的文件!");
11
12 }
13 if(!file.isEmpty()){
14 15
16 System.out.println("--");
17 byte[] bytes = file.getBytes();
18 Path path = Paths.get("C://tool//Project//demo3//src//main//resources//static//img//" + file.getOriginalFilename());
19 Files.write(path, bytes);
20 String str = "上传成功!";
21 model.addAttribute("emg",str);
22 model.addAttribute("image",file.getOriginalFilename());
23 System.out.println(path);
24 }
25 return "uploadPage";
26 }
27 }
3.application.properties
#spring.servlet.multipart.enabled=false
spring.servlet.multipart.enabled=true
注意:Spring Boot默认实例化了一个MultipartResolver(StandardServletMultipartResolver);
application.properties中的“spring.servlet.multipart.enabled”默认(不写)为true。设置false在这里会报错。