表单项 type=“file”
表单的提交方式是post
表单的enctype属性是多部份表单形势, 及 enctype=“multipart/form-data”
创建一个upload.jsp文件
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Titletitle>
head>
<body>
<form action="${pageContext.request.contextPath}/user/quick22" method="post" enctype="multipart/form-data">
名称<input type="text" name="username"><br/>
文件<input type="file" name="upload"><br/>
<input type="submit" name="提交"><br/>
form>
body>
html>
当form表单修改为多部份表单时,request.getParameter()将失效
enctype="multipart/form-data"
时, form表单的正文内容格式是: key=value&key=value&key=value
当form表单的enctype取值为multipart/form-data时, 请求正文内容就变成多部份形式
导入fileupload和io坐标, 在pom.xml文件中导入
<dependency>
<groupId>commons-fileuploadgroupId>
<artifactId>commons-fileuploadartifactId>
<version>1.3.1version>
dependency>
<dependency>
<groupId>commons-iogroupId>
<artifactId>commons-ioartifactId>
<version>2.3version>
dependency>
配置文件上传解析器, 在spring-mvc.xml上配置
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"/>
<property name="maxInMemorySize" value="500000"/>
bean>
编写文件上传代码
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping(value = "/quick22")//请求映射
@ResponseBody
public void save22(String username, MultipartFile uploadFile) throws IOException {
System.out.println(username);
System.out.println(uploadFile);
}
}
//获得文件上传名称
String originalFilename = uploadFile.getOriginalFilename();
uploadFile.transferTo(new File("E:\\upload\\"+originalFilename));
在单文件上传的基础上加就行了
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Titletitle>
head>
<body>
<form action="${pageContext.request.contextPath}/user/quick22" method="post" enctype="multipart/form-data">
名称<input type="text" name="username"><br/>
文件<input type="file" name="uploadFile"><br/>
文件<input type="file" name="uploadFile2"><br/>
<input type="submit" name="提交"><br/>
form>
body>
html>
@RequestMapping(value = "/quick22")//请求映射
@ResponseBody
public void save22(String username, MultipartFile uploadFile, MultipartFile uploadFile2) throws IOException {
//获得文件上传名称
String originalFilename = uploadFile.getOriginalFilename();
uploadFile.transferTo(new File("E:\\upload\\"+originalFilename));
//获得文件上传名称
String originalFilename2 = uploadFile.getOriginalFilename();
uploadFile.transferTo(new File("E:\\upload\\"+originalFilename2));
}
如果上传的文件过多, 可以采用数组结合循环遍历的方式
@RequestMapping(value = "/quick23")//请求映射
@ResponseBody
public void save23(String username, MultipartFile[] uploadFile) throws IOException {
System.out.println(username);
for (MultipartFile multipartFile : uploadFile) {
String originalFilename = multipartFile.getOriginalFilename();
multipartFile.transferTo(new File("E:\\upload\\" + originalFilename));
}
}