在Soring MVC里面对于文件的上传操作依然使用了FileUpload组件(几乎所有的MVC开发框架都使用FileU pload上传组件,这个组件只有在结合框架的时候才好用).
如果要想使用SpringMVC文件上传,则必须使用org.springframework.web.multipart.commons.CommonsMultipartFile
这个类来进行处理,这个类提供有如下的处理方法:
取得上传文件的MIME类型:
public java.lang.String getContentType()判断是否有上传文件
public boolean isEmpty()
取得上传文件的长度
public long getSize()
取得上传文件的输入流
public java.io.InputStream getInputStream()
范例:在applicationContext.xml文件里面定义上传操作类
设置工具限制类:
- org.springframework.web.multipart.commons.CommonsMultipartResolver

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 上传的文件大小5m -->
<property name="maxUploadSize" value="5242880"/>
<!-- 在内存中保存的文件大小2m -->
<property name="maxInMemorySize" value="2097152"/>
</bean>
随后接收实现文件的上传操作,
接收上传文件:org.springframework.web.multipart.support.MultipartFilter(CommonsMultipartFile的父接口)
范例:定义Action实现文件的接收
package cn.zwb.action;
import java.io.IOException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import cn.zwb.vo.Type;
@RequestMapping("/pages/*")
public class UploadAction {
public ModelAndView insert(Type type,MultipartFile pic) throws IOException{
System.out.println("[类型名称]"+type.getTypeTitle());
System.out.println("[文件类型]"+pic.getContentType());
System.out.println("[文件大小]"+pic.getSize());
System.out.println("[是否为空]"+pic.isEmpty());
System.out.println("[数据流]"+pic.getInputStream());
return null;
}
}
文件上传不可忽视的就是表单,必须使用表单上传文件,
范例:定义上传页面
<body>
<form action="pages/insert_type.action" method="POST" enctype="multipart/form-data">
消息类型:<input type="text" id="typeTile" name="typeTile" value="近期头条"><br>
上传文件:<input type="text" id="pic" name="pic" ><br>
<input type="submit" value="提交">
<input type="reset" value="重置">
</form>
</body>
现在基本的上传操作已经可以正常实现了,这固然是件好事,但是这里面还会存在一个小小的问题.
如果现在超过了预计的上传文件大小,那么在没有处理的情况下就会出现500的错误提示,并且出现500错误:org.springframework.web.multipart.MaxUploadSizeExceededException
可以在web.xml里面配置
<error-page>
<error-code>500</error-code>
<location>/error.jsp</location>
</error-page>
在spring MVC里面并没有将所有的错误信息都交给了WEB容器完成,而是说它可以自己来处理出现的异常
范例:在applicationContext文件之中处理异常信息
org.springframework.web.servlet.handler.SimpleMappingExceptionResolver
<bean id="exceptionMapping" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">
errors
</prop>
</props>
</property>
</bean>
由于整个项目里面已经配置好了安全的访问操作,所以此时的路径会自动利用之前的安全访问路径而后进行跳转也就是说需要在/WEB-INF/下提供有一个errors的信息
112

被折叠的 条评论
为什么被折叠?



