內容來源:http://blog.csdn.net/kouwoo/article/details/40507565
一、配置文件:
SpringMVC 用的是 的MultipartFile來進行文件上傳 所以我們首先要配置MultipartResolver:用於處理表單中的file
applicationContext.xml中
- <!-- 配置MultipartResolver 用於文件上傳 使用spring的CommosMultipartResolver -->
- <beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
- p:defaultEncoding="UTF-8"
- p:maxUploadSize="5400000"
- p:uploadTempDir="fileUpload/temp"
- >
- </beans:bean>
- 其中屬性詳解:
defaultEncoding="UTF-8" 是請求的編碼格式,默認為iso-8859-1
maxUploadSize="5400000" 是上傳文件的大小,單位為字節
uploadTempDir="fileUpload/temp" 為上傳文件的臨時路徑 -
- <body>
- <h2>文件上傳實例</h2>
- <form action="fileUpload.html" method="post" enctype="multipart/form-data">
- 選擇文件:<input type="file" name="file">
- <input type="submit" value="提交">
- </form>
- </body>
-
- /通過Spring的autowired注解獲取spring默認配置的request
- @Autowired
- private HttpServletRequest request;
- /***
- * 上傳文件 用@RequestParam注解來指定表單上的file為MultipartFile
- *
- * @param file
- * @return
- */
- @RequestMapping("fileUpload")
- public String fileUpload(@RequestParam("file") MultipartFile file) {
- // 判斷文件是否為空
- if (file!=null) {
- try {
- // 文件保存路徑
- String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/"
- + file.getOriginalFilename();
- // 轉存文件
- file.transferTo(new File(filePath));
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- // 重定向
- return "redirect:/list.html";
- }
- 個人感想:以上代碼都是從別處弄來的,感覺沒有特別難的,我的項目中唯一一個不同的地方是,把文件名字重新改了下,只需如下修改
- String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/" +(UUId+文件名)+.后綴名
- File targetFile = new File(filePath);
- file.transferTo(new File(filePath));
- 注意new File() 還有一個帶倆參數的構造方法new file(path,fileName);其實這都無所謂了,new出來的東西是一樣的,既有路徑又有文件名