1.添加依赖
XML
<!--文件上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
2.配置文件上传解析器
XML
<!--配置文件上传解析器-->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5242880" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
3.index.jsp
html
<form action="/account/upload" method="post" enctype="multipart/form-data">
文件: <input type="file" name="upload"></input>
<input type="submit" value="提交">
</form>
4.测试
java
@Controller
@RequestMapping("/account")
public class AccountController {
@RequestMapping("/upload")
public String upload(MultipartFile img , HttpServletRequest request, Model model) throws IOException {
//1.获取要上传的文件目录
String realPath = request.getSession().getServletContext().getRealPath("/upload");
//2.根据文件上传的目录创建File对象,如果不存在则创建1个File对象
File file = new File(realPath);
if (!file.exists()){
//创建一个file对象
file.mkdirs();
}
//获取文件上传名称
String fileName= img.getOriginalFilename();
//3.完成文件上传
img.transferTo(new File(realPath,fileName));
model.addAttribute("msg","你好,Spring MVC");
return "success";
}
}
5.结果:
6.总结:
文件上传
1、pom.xml
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
2、配置上传解析器
<!--配置文件上传解析器-->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5242880" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
3、form
<form action="/account/upload" method="post" enctype="multipart/form-data">
图片:<input type="file" name="img"><br>
<input type="submit" value="上传">
</form>
3、文件上传
@RequestMapping("/upload")
public String upload(MultipartFile img) throws IOException {
//1、获得tomcat的路径
//2、创建uploads目录
//3、上传文件
}