SpringMVC进行文件上传
SpringMVC自带的文件上传,上传多个文件时,同名的文件不能重复上传,解决这一问题,可以将文件名以上传时的时间戳+随机数命名,这样,基本上不可能出现重复的文件名
- spring-mvc.xml中
<!-- 文件上传 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置默认字符集 -->
<property name="defaultEncoding" value="UTF-8"/>
<!-- 设置上传文件的大小(10兆) -->
<property name="maxUploadSize" value="10000000"/>
</bean>
- jsp中
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上传</title>
</head>
<body>
<form action="upload" method="post" enctype="multipart/form-data">
<table>
<tr>
<th colspan="2">上传文件</th>
</tr>
<tr>
<td>文件一</td>
<td><input type="file" name="file" /></td><!-- name必须和Controller中的参数名相同 -->
</tr>
<tr>
<td>文件二</td>
<td><input type="file" name="file" /></td>
</tr>
<tr>
<td>文件三</td>
<td><input type="file" name="file" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="上传文件" /></td>
</tr>
</table>
</form>
</body>
</html>
- controller中
@Controller
public class FileUploadController {
@RequestMapping("/upload")
public String uploadFile(@RequestParam("file")MultipartFile[] files) throws IllegalStateException, IOException {
Date date = new Date();
for(MultipartFile file:files) {
String fileOldName = file.getOriginalFilename().replace(".", "-");
Random random = new Random();
String fileNewName = date.getTime()+random.nextInt(100)+"."+fileOldName.split("-")[1];
file.transferTo(new File("D:\\workspace\\SpringMVCDemo03\\upload\\"+fileNewName));
}
return "redirect:success.jsp";
}
}
- 效果
- 选择相同的图片
- 上传成功
- 进入目录查看结果
- 选择相同的图片