`
piperzero
  • 浏览: 3456726 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
文章分类
社区版块
存档分类
最新评论

spring2.5 mvc使用注解upload上传文件

 
阅读更多

对于spring mvc来说2.0以后大量使用注解确实简单很多,最近在一个项目使用spring mvc遇到上传文件问题,由于使用了注解所以网上没有找到相关使用注解上传文件的。官方文档又没有更新都是老的,看了一些源码这才解决。
使用注解很简单。
写个例子:控制器类 FileUploadController.java

package org.upload.test;  
   
import org.springframework.stereotype.Controller;  
import java.io.FIle;  
import org.springframework.web.bind.annotation.RequestParam;  
import org.springframework.web.multipart.MultipartFile;  
/** 
 * FileUploadController for the file upload . 
 * 
 * @author lhbdir 
 * @since 09.01.2008 
 */  
@Controller  
public class FileUploadController {  
  @RequestMapping("/imageUpload")  
   public String processImageUpload(  
     @RequestParam("imageFile") MultipartFile image) throws IOException {  
         FileCopyUtils.copy(image.getBytes(),new File("c:/"+image.getOriginalFilename()));  
     return "imageList";  
   }  
 }  


@RequestParam("imageFile") MultipartFile image 是注解映射页面上传文件标签name属性,
页面 imageList.jsp里的内容,加上下面的就可以了。

<table border="1" cellspacing="0" cellpadding="5">  
<form action="imageUpload" method="post" encType="multipart/form-data">  
  <tr<td>Content</td><td> <input type="imageFile" name="image">  
<br></td></tr>  
  <tr><td colspan="2"><input type="submit" value="Upload image"></td></tr>  
</form>  
</table> 


<input type="file" name="imageFile">此标签name与控制器类注解要一样.
下面的配置文件要写好,web.xml跟applicationContext.xml不用加什么跟正常的spring mvc一样配置就可以了,
servletName-servlet.xml (servletName是你配置在web.xml里的,不明白的去看一下spring MVC配置文档)

里加入以下代码做文件上传类的绑定:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>

别忘了加入commons里的fileupload跟io两个JAR包,这样就可以了。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics