导入 jar 包:commons-io-2.0.jar
用CommonsMultipartFile时必须是commons-io-2.0.jar以上版本
1.文件上传页面 jsp
<form action="upload.do" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>上传人:</td>
<td><input type="text" name="user" value="holly"></td>
</tr>
<tr>
<td>选择图片:</td>
<td><input type="file" name="uploadfile"></td>
</tr>
<tr>
<td colspan="2" align="center"></td>
<td><input type="submit" value="提交"></td>
</tr>
</table>
</form>
2.配置 springMVC-serlvet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
">
<!-- 1.mvc注解驱动 -->
<mvc:annotation-driven/>
<!-- 2.全局扫描包 -->
<context:component-scan base-package="com"/>
<!-- 上传下载配置 :公共的二进制处理器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 上传时默认的编码格式 -->
<property name="defaultEncoding" value="UTF-8"/>
<!--指定上传的总的文件大小的总和。默认是200kb。-1是不设限 -->
<property name="maxUploadSize" value="-1"/>
</bean>
<!--
简单的映射异常 :文件超过指定大小的异常配置
注意:id的值是固定的
-->
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">
error.jsp
</prop>
</props>
</property>
</bean>
</beans>
3. controller
@Controller
public class UploadController {
/*
* 用CommonsMultipartFile时必须是commons-io-2.0.jar以上版本
*/
@RequestMapping("/upload.do")
public String queryFileDate(HttpServletRequest request,@RequestParam("uploadfile") CommonsMultipartFile file) throws IOException{
//判断文件对象是否存在
if (file!=null) {
// 1.获取文件名
String filename=file.getOriginalFilename();
System.out.println("filename:"+filename);
// 2. 获取上传的文件路径
String path=request.getSession().getServletContext().getRealPath("upload/"+filename);
System.out.println("path:"+path);
// 3.创建文件流指定写入路径
File uploadpath=new File(path);
// 4.上传文件
FileUtils.copyInputStreamToFile(file.getInputStream(), uploadpath);
System.out.println("上传成功!");
return "/success.jsp";
}else {
System.out.println("文件对象没有找到!");
}
return "/error.jsp";
}