SpringMVC 文件上传

SpringMVC文件上传


jsp代码:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
</head>

<body>
	<form action="${pageContext.request.contextPath }/mvc/fileUpload.do" enctype="multipart/form-data" method="post">
		<input type="file" name="uploadFile"><br/>
		<input type="file" name="uploadFile1"><br/>
		<input type="file" name="uploadFile2"><br/>
		<input type="file" name="uploadFile3"><br/>
		<input type="file" name="uploadFile4"><br/>
		<input type="file" name="uploadFile5"><br/>
		<input type="submit">
	</form>
</body>
</html>

springmvc-serlvet.xml代码:

<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver">
	<property name="defaultEncoding" value="utf-8"></property>
	<property name="maxUploadSize" value="1024000"></property>
	<property name="maxInMemorySize" value="10240000"></property>
</bean>
Java代码:

@RequestMapping("fileUpload")
	public String fileUpload(HttpServletRequest request) {
		// 设置文件存放目录
		String realPath = request.getServletContext().getRealPath("fileUpload");
		// 创建一个文件
		File file = new File(realPath);
		// 判断文件目录是否存在
		if (!file.isDirectory()) {
			//不存在则创建
			file.mkdir();
		}
		// 获取解析器
		CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getServletContext());
		// 判断请求是否为multipart类型的
		if (commonsMultipartResolver.isMultipart(request)) {
			// 将请求转换为MultipartHttpServletRequest
			MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
			// 获取上传文件名的迭代器
			Iterator<String> fileNames = multipartHttpServletRequest.getFileNames();
			// 遍历迭代器
			while (fileNames.hasNext()) {
				// 获取第一个文件
				MultipartFile file2 = multipartHttpServletRequest.getFile(fileNames.next());
				// 获取文件的原始文件名
				String originalFilename = file2.getOriginalFilename();
				// 得到一个转换时间格式的转换器
				SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSS");
				// 创建一个文件名:保存文件目录路径+/(File.separator)+当前时间+原始文件名
				String path = realPath + File.separator + simpleDateFormat.format(new Date()) + originalFilename;
				try {
					// 保存文件
					file2.transferTo(new File(path));
				} catch (IllegalStateException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return "homepage";
	}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值