?upload.jsp文件:
?
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/quick15" method="post" enctype="multipart/form-data">
名称<input type="text" name="username"><br/>
文件<input type="file" name="upload"><br/>
<input type="submit" value="提交">
</form>
</body>
</html>
?
①导入fileupload和io坐标
<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.6</version>
</dependency>
②配置文件上传解析器
文件上传解析器的id是固定的,一定得是multipartResolver
<!--配置文件上传解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"></property>
<property name="maxUploadSize" value="500000"/>
</bean>
③编写文件上传代码
@RequestMapping("/quick15")
@ResponseBody
// 参数名称要和form表单中的name保持一致
public void save15(String username, MultipartFile upload){
System.out.println("------------------------");
System.out.println(username);
System.out.println(upload);
}
保存文件:
@PostMapping("/quick15")
@ResponseBody
public void save15(MultipartFile upload,String username) throws IOException {
String originalFilename = upload.getOriginalFilename();
File file = new File("C:\\Users\\think\\Desktop\\upload\\" + originalFilename);
upload.transferTo(file);
?
}
请求:http://localhost:8080/upload.jsp
?
|