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>
可以通過火狐瀏覽器查看
提交上傳成功,可以查看報文信息
可以在請求中查看到傳遞文件的信息
它以---加數字開始 以---加數字結束,中間有文件內容
傳遞圖片時請求中的報文信息