當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
初学SpringMVC,使用MVC进行文件上传
生活随笔
收集整理的這篇文章主要介紹了
初学SpringMVC,使用MVC进行文件上传
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
最近在做一個文件上傳的功能,走了不少彎路,話不多說,直接上代碼:
導(dǎo)入各種jar包,首先是applicationContext.xml配置文件中:
1 <!-- 配置文件解析器 --> 2 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 3 </bean> View Code寫兩個前端頁面:upLoad.jsp
1 <body> 2 <form action="upload.do" method="post" enctype="multipart/form-data"> 3 姓名:<input type="text" name="username"/><br> 4 頭像:<input type="file" name="mf"/><br> 5 姓名:<input type="submit" value="上傳"/> 6 </form> 7 </body> View Codeshow.jsp
1 <body> 2 <h1>head image</h1> 3 <img alt="" src="${image }" style="width: 400px;height: 500px"> 4 </body> View Code然后進入正題,寫一個上傳的戰(zhàn)士頁面的controller
@RequestMapping("/toUpload.do") //SpringMVC的映射標注public String toUpload(){return "upload";}然后
1 @Controller 2 public class FileUploadController { // MultipartFile 用于接受文件對象 3 @RequestMapping("/upload.do") // MultipartFile用于接受用戶名和數(shù)據(jù),否則文件上傳時候也上encytype后悔接收不到數(shù)據(jù) 4 public String upload(String username, MultipartFile mf, HttpServletRequest req) { 5 6 System.out.println(username + "||" + mf.getOriginalFilename() + "||" + mf.getSize()); 7 // 把文件寫入響應(yīng)路徑下 8 String realpath = req.getServletContext().getRealPath("images");// 獲取到當前文件夾的真是路徑 9 String orName = mf.getOriginalFilename();// 獲取文件的原始名字 10 String fileName = System.currentTimeMillis() + orName.substring(orName.lastIndexOf("."));// 修改上傳文件的名字,時間加后綴 11 String filePath = realpath + "/" + fileName; 12 System.out.println(filePath); 13 File file = new File(filePath);// 創(chuàng)建一個文件對象 14 try { 15 mf.transferTo(file);// 將文件寫入到路徑中 16 } catch (IllegalStateException e) { 17 e.printStackTrace(); 18 } catch (IOException e) { 19 e.printStackTrace(); 20 } 21 req.setAttribute("image", "images/" + fileName); 22 return "show"; 23 } 24 } View CodeOK!,大功告成!
轉(zhuǎn)載于:https://www.cnblogs.com/hx1098/p/9326035.html
總結(jié)
以上是生活随笔為你收集整理的初学SpringMVC,使用MVC进行文件上传的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java之初学线程
- 下一篇: 【洛谷P1538】迎春舞会之数字舞蹈