1.前端界面
文件上传三大要素:
type="file",method="post",enctype="multipart/form-data"
<%--
Created by IntelliJ IDEA.
User: 75978
Date: 2021/10/3
Time: 16:20
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/user/quick23" method="post" enctype="multipart/form-data">
<%--表明是第几个User对象的username,age--%>
名称<input type="text" name="username"><br/>
文件<input type="file" name="uploadFile">
文件<input type="file" name="uploadFile">
<input type="submit" value="tijiao">
</form>
<form action="${pageContext.request.contextPath}/user/quick22" method="post" enctype="multipart/form-data">
<%--表明是第几个User对象的username,age--%>
名称<input type="text" name="username"><br/>
文件<input type="file" name="uploadFile">
文件<input type="file" name="uploadFile2">
<input type="submit" value="tijiao">
</form>
</body>
</html>
2.文件接收
1.导入fileupload和io坐标
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.3</version>
</dependency>
2.配置解析器
<!-- 配置文件上传解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"></property>
<property name="maxUploadSize" value="500000"></property>
</bean>
3.编写代码
/**
* 文件上传接收
*/
@RequestMapping(value = "/quick22")
@ResponseBody
public void save22(String username, MultipartFile uploadFile,MultipartFile uploadFile2) throws IOException {
System.out.println(username);
//获得上传文件名称
String filename = uploadFile.getOriginalFilename();
uploadFile.transferTo(new File("D:\\upload\\"+filename));
String filename2 = uploadFile2.getOriginalFilename();
uploadFile.transferTo(new File("D:\\upload\\"+filename2));
}
/**
* 多文件上传接收
*/
@RequestMapping(value = "/quick23")
@ResponseBody
public void save2(String username, MultipartFile[] uploadFile) throws IOException {
System.out.println(username);
//获得上传文件名称
for (MultipartFile multipartFile : uploadFile) {
String originalFilename = multipartFile.getOriginalFilename();
multipartFile.transferTo(new File("D:\\upload\\"+originalFilename));
}
}