SpringMVC實現檔案上傳功能
阿新 • • 發佈:2022-03-25
檔案上傳
檔案上傳要求form表單的請求方式必須為post,並且新增屬性enctype="multipart/form-data"
SpringMVC中將上傳的檔案封裝到MultipartFile物件中,通過此物件可以獲取檔案相關資訊
缺一不可
1.請求方式必須為post
2.屬性enctype="multipart/form-data"
上傳步驟:
a>新增依賴:
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency>
b>在SpringMVC的配置檔案中新增配置:
<!--必須通過檔案解析器的解析才能將檔案轉換為MultipartFile物件-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
c>控制器方法:
/** * 實現檔案上傳功能 * @param photo * @param session * @return * @throws IOException */ @RequestMapping("/testUp") public String testUp(MultipartFile photo, HttpSession session) throws IOException { //獲取上傳的檔案的檔名 String fileName = photo.getOriginalFilename(); //處理檔案重名問題 (獲取字尾名) String hzName = fileName.substring(fileName.lastIndexOf(".")); fileName = UUID.randomUUID().toString() + hzName; //獲取伺服器中photo目錄的路徑 ServletContext servletContext = session.getServletContext(); String photoPath = servletContext.getRealPath("photo"); File file = new File(photoPath); //如果伺服器中不存在photo路徑,則建立一個 if(!file.exists()){ file.mkdir(); } //最終的上傳路徑 //File.separator 檔案分隔符/ String finalPath = photoPath + File.separator + fileName; //實現上傳功能 photo.transferTo(new File(finalPath)); return "target"; }
d>html程式碼
<h1>上傳測試</h1>
<form th:action="@{/testUp}" method="post" enctype="multipart/form-data">
頭像:<input type="file" name="photo"><br>
提交:<input type="submit" name="submit"><br>
</form>
測試
上傳成功