文件上传的原理
细节说明:
1.上传jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>上传文件</title>
</head>
<body>
<h3>文件上传</h3>
<form action="user/fileupload2" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="upload"/><br/>
<input type="submit" value="上传文件"/></form>
</body>
</html>
2.在 springmvc.xml 中配置文件解析器对象
<!-- 配置文件解析器对象,要求id名称必须是multipartResolver -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- maxUploadSize 设置上传文件最大值10M-->
<property name="maxUploadSize" value="10485760"/>
</bean>
3.后台逻辑代码,使用 MultipartFile 对象来代表文件对象
(注: 上传的文件名需要和 MultipartFile 的参数名称相同)
// fileupload1
@RequestMapping(value = "/fileupload2")
public String fileupload2(HttpServletRequest request, MultipartFile upload) throws Exception
{
System.out.println(" SpringMVC传统方式文件上传...");
// 先获取到要上传的文件目录
String path = request.getSession().getServletContext().getRealPath("/uploads");
// 创建File对象,一会向该路径下上传文件
File file = new File(path);
// 判断路径是否存在,如果不存在,创建该路径
if (!file.exists())
{
file.mkdirs();
}
// 获取到上传文件的名称
String filename = upload.getOriginalFilename();
String uuid = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
filename = uuid + "_" + filename;
// 上传文件
upload.transferTo(new File(file, filename));
return "success";
}