完成多文件上传(SpringMVC)

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";
	}
}
  • 效果
    • 选择相同的图片
      在这里插入图片描述
    • 上传成功
      在这里插入图片描述
    • 进入目录查看结果
      在这里插入图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值