1.概述
Apache 提供文件上传包 Commons-FileUpload 。 SpringMVC整合了这个包,进行了进一步的封装
文件上传相关的两个包:
2.文件上传表单必须满足如下三个条件
- 文件上传项必须有name属性
- 表单必须是Post提交
- 表单必须是enctype="multipart/form-data"
enctype="multipart/form-data(表示用附件的方式发送表单),否则默认就把文件名传递了
提交时请求主体发生改变
需要满足的3个条件如下
在springmvc.xml中需要配置文件上传工具类
<!--配置文件上传工具类-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
3.代码实现
控制器中的代码
package cn.tedu.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
@Controller
@RequestMapping("/my01")
public class MyController01 {
/**
* 文件上传
*/
@RequestMapping("/test01.action")
public void test01(MultipartFile fx) throws IOException {
fx.transferTo(new File("E://"+fx.getOriginalFilename()));
}
}
springmvc.xml中的代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--配置包扫描-->
<context:component-scan base-package="cn.wyy.web"/>
<!--配置注解方式mvc-->
<mvc:annotation-driven/>
<!--配置视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--配置文件上传工具类-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
</beans>
前端界面代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>index.jsp</title>
</head>
<body>
<h1>文件上传案例</h1>
<form action="${pageContext.request.contextPath}/my01/test01.action"
method="post"
enctype="multipart/form-data"
>
选择文件:<input type="file" name="fx"/>
<br/>
<input type="submit"/>
</form>
</body>
</html>
可以通过火狐浏览器查看
提交上传成功,可以查看报文信息
可以在请求中查看到传递文件的信息
它以---加数字开始 以---加数字结束,中间有文件内容
传递图片时请求中的报文信息