在load.jsp中简单写上一些测试代码:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%--enctype:提交数据格式--%>
<form action="${pageContext.request.contextPath}/user/quick16" method="post" enctype="multipart/form-data">
名称:<input type="text" name="username">
文件:<input type="file" name="upload">
<input type="submit" value="提交">
</form>
</body>
</html>
配置maven坐标:
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
在springMVC.xml中配置文件解析器:
<!-- 配置文件上传解析器,id一定要一样-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 文件编码格式-->
<property name="defaultEncoding" value="UTF-8"></property>
<!-- 文件最大的大小-->
<property name="maxUploadSize" value="50000"></property>
</bean>
在controller.java中配置:
@RequestMapping("/quick16")
@ResponseBody
public void save16(String username, MultipartFile uploadFile) throws IOException {
System.out.println("username:"+username);
// 获取文件名称
String originalFilename = uploadFile.getOriginalFilename();
// 将文件存储到本地
uploadFile.transferTo(new File("/Users/cu/Desktop/ceshi/"+originalFilename));
}