用Springmvc传文件

来源:互联网 发布:知乎怎么提问 编辑:程序博客网 时间:2024/06/14 19:35

今天需要用到文件上传,用的是spring框架。在网上搜了好久没找到合适的代码。经过师傅的指点5分钟搞定。觉得挺简单的!

 

1.首先在applicationContext.xml文件中配置文件上传解决器

 

[html] view plaincopy
  1. <!-- 文件上传拦截 -->  
  2.     <bean id="multipartResolver"  
  3.         class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
  4.     </bean>  

2.上传的jsp页面、很简单

[html] view plaincopy
  1. <form action="/gouwuche3/goods/add.htm" method="post" enctype="multipart/form-data" >  
  2.     <table align="center" border="1">  
  3.         <tr>  
  4.             <td colspan="2">商品信息</td>  
  5.         </tr>  
  6.           
  7.         <tr>  
  8.             <td>商品名字</td><td><input name="goodsName" id="goodsName" type="text" /></td>  
  9.         </tr>  
  10.         <tr>  
  11.             <td>商品价格</td><td><input name="goodsPrice" id="goodsPrice" type="text" /></td>  
  12.         </tr>  
  13.         <tr>  
  14.             <td>商品描述</td><td><input name="goodsDes" id="goodsDes" type="text" /></td>  
  15.         </tr>  
  16.          <tr>  
  17. <span style="color:#ff6666;">           <td>上传照片</td><td><input type="file" name="file" /></td>  
  18. </span>     </tr>  
  19.         <tr><td colspan="2"><input type="submit" value="确认" /></td></tr>  
  20.       
  21.       
  22.       
  23.     </table>  
  24. </form>  

注意红色的代码,是上传文件用的。

 

 

3.在controller中执行文件上传功能。

 

[java] view plaincopy
  1. @RequestMapping(value = "/add")  
  2. /MultipartFile来自:org.springframework.web.multipart.MultipartFile;  
[java] view plaincopy
  1. public ModelAndView addGoods( HttpServletRequest request, HttpSession session,  
  2.        <span style="color:#ff0000;"@RequestParam("file") MultipartFile file</span>) {  
  3.     ModelAndView mav = new ModelAndView();  
  4.     if (!file.isEmpty()) {  
  5.   
  6.         String path = request.getContextPath() + "/jsp/";  
  7.         String fileName = file.getOriginalFilename();  
  8.   
  9.         try {  
  10.             String tomcatPath = request.getServletContext().getRealPath("/image//"); //得到保存的路径  
  11.             FileCopyUtils.copy(file.getBytes(), new File(tomcatPath +"/" +  fileName));//FileCopyUtils来自org.springframework.util.FileCopyUtils  
  12.   
  13.         } catch (IOException e) {  
  14.             // TODO Auto-generated catch block  
  15.             e.printStackTrace();  
  16.         }  
  17.   
  18.                }  
  19.   
  20.     mav.setViewName("test");  
  21.     return mav;  
  22.   
  23. }  


 

这就完事了。。。

0 0
原创粉丝点击