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";
}