一、案例
1.1 配置application.properties
#主配置文件,配置了這個會優先讀取里面的屬性覆蓋主配置文件的屬性 spring.profiles.active=dev server.port=8888 logging.config=classpath:log4j2-dev.xml spring.mvc.view.prefix: /WEB-INF/templates/ spring.mvc.view.suffix: .jsp
- spring.http.multipart.enabled=true #默認支持文件上傳.
- spring.http.multipart.file-size-threshold=0 #支持文件寫入磁盤.
- spring.http.multipart.location= # 上傳文件的臨時目錄
- spring.http.multipart.max-file-size=1Mb # 最大支持文件大小
- spring.http.multipart.max-request-size=10Mb # 最大支持請求大小
1.2 編寫IndexController
- 該控制器只用於處理 “/” 和“/index”請求,使之跳轉到index.jsp頁面
package com.shyroke.controller; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller @RequestMapping(value = "/") public class IndexController { @RequestMapping(value="index") public String index() { return "index"; } @RequestMapping() public String index2() { return "index"; } }
1.3 編寫index.jsp
<body> <form method="POST" enctype="multipart/form-data" action="/file/upload"> 文件:<input type="file" name="file" /> <input type="submit" value="上傳" /> </form> </body>
1.4 編寫FileController
package com.shyroke.controller; import java.io.File; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; @Controller @RequestMapping(value = "/file") public class FileController { private static final Logger logger = LoggerFactory.getLogger(FileController.class); @RequestMapping(value = "upload") @ResponseBody public String upload(@RequestParam("file") MultipartFile file) { if (file.isEmpty()) { return "文件為空"; } // 獲取文件名 String fileName = file.getOriginalFilename(); logger.info("上傳的文件名為:" + fileName); // 獲取文件的后綴名 String suffixName = fileName.substring(fileName.lastIndexOf(".")); logger.info("上傳的后綴名為:" + suffixName); // 文件上傳路徑 String filePath = "E://"; // 解決中文問題,liunx下中文路徑,圖片顯示問題 // fileName = UUID.randomUUID() + suffixName; File dest = new File(filePath + fileName); // 檢測是否存在目錄 if (!dest.getParentFile().exists()) { dest.getParentFile().mkdirs(); } try { file.transferTo(dest); return "上傳成功"; } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return "上傳失敗"; } }
1.5 結果