通过SpringMVC实现文件上传
和servlet方式的本质一样,都是通过commons-fileupload.jar和commons-io.jar。
SpringMVC可以简化文件上传的代码,实现MultipartResolver接口。
具体步骤:(直接使用CommonsMultipartResolver实现文件上传)
1.jar包
2.配置CommonsMultipartResolver
将其加入SpringMVC。
<!--配置CommonsMultipartResolver,实现文件上传,将其加入SpringMVC。
id值固定,SpringIOC容器初始化时会自动寻找 这个id,并将其加入IOC容器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"></property>
<!--上传单个文件的最大值,单位byte, -1 表示无限制-->
<property name="maxUploadSize" value="102400"></property>
</bean>
3.处理方法
//测试文件上传 @RequestMapping(value = "testUpload") public String testUpload(@RequestParam("desc") String desc, @RequestParam("file") MultipartFile file) throws IOException { System.out.println("文件描述信息:"+desc); //jsp中上传的文件 InputStream input=file.getInputStream(); //IO String fileName=file.getOriginalFilename(); OutputStream output=new FileOutputStream("d:\\"+fileName); //将file上传到服务器的某个硬盘中 byte[] bs=new byte[1024]; int len=-1; while ((len=input.read(bs))!=-1){ output.write(bs,0,len); } output.close(); input.close(); System.out.println("上传成功"); return "success"; }
<form action="SpringMVCHandler/testUpload" method="post" enctype="multipart/form-data"> <input name="file" type="file"> 描述:<input name="desc" type="text"> <input type="submit" value="上传"> </form>
拦截器
拦截器与过滤器相同。
SpringMVC:要想实现拦截器,必须实现一个接口HandlerInterceptor。
具体步骤:
1.编写拦截器;
public class MyInterceptor implements HandlerInterceptor{ @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { System.out.println("拦截请求"); return true; //true:拦截操作之后,放行; false: 拦截之后不放行,请求终止; } @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { System.out.println("拦截响应"); } @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { System.out.println("视图被渲染完毕"); } }
2.配置:将编写的拦截器放入SpringMVC中;
<!--将自己写的拦截器加入SpringMVC;默认拦截全部请求·-->
<mvc:interceptors>
<!--配置具体的拦截路径-->
<mvc:interceptor>
<!--指定拦截的路径,基于ant风格-->
<mvc:mapping path="/**"/>
<!--指定不拦截的请求-->
<mvc:exclude-mapping path="/SpringMVCHandler/testUpload"></mvc:exclude-mapping>
<bean class="org.ghl.interceptor.MyInterceptor"></bean>
</mvc:interceptor>
<!--配置具体的拦截路径-->
<mvc:interceptor>
<!--指定拦截的路径,基于ant风格-->
<mvc:mapping path="/**"/>
<!--指定不拦截的请求-->
<mvc:exclude-mapping path="/SpringMVCHandler/testUpload"></mvc:exclude-mapping>
<bean class="org.ghl.interceptor.MySecondInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
两次拦截器结果: