1.maven坐标
<!-- 必选项 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<!-- commons-io 可选 会自动导入 -->
2.springmvc.xml配置
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="104857600" />
<property name="maxInMemorySize" value="4096" />
<property name="defaultEncoding" value="UTF-8"/>
</bean>
3.controller层
@RequestMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest req)
throws IllegalStateException, IOException {
// 判断文件是否为空,空则返回失败页面
if (file.isEmpty()) {
return "failed";
}
// 获取文件存储路径(绝对路径)
String path = req.getServletContext().getRealPath("/WEB-INF/file");
// 获取原文件名
String fileName = file.getOriginalFilename();
// 创建文件实例
File filePath = new File(path, fileName);
// 如果文件目录不存在,创建目录
if (!filePath.getParentFile().exists()) {
filePath.getParentFile().mkdirs();
System.out.println("创建目录" + filePath);
}
// 写入文件
file.transferTo(filePath);
return "success";
}