1.在SpringMVC的配置文件中
配置文件上传的解析器:
<!-- 配置文件上传的解析器,不配置的话参数不能传入 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize">
<value>5242880</value>
</property>
</bean>
2.文件上传的jsp页面:(post请求,enctype="
multipart/form-data
")
注:
jsp页面获取项目路径:${pageContext.request.contextPath}
java代码获取项目路径:
request
.
getContextPath
()
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
...
<%
pageContext.setAttribute("APP_PATH", request.getContextPath());
%>
</head>
<body>
<form action="${APP_PATH}/user" method="post" enctype="multipart/form-data">
上传文件:<input type="file" name="file"/>
提交:<button type="submit"/>
</form>
</body>
...
3.控制器处理上传文件的请求:
@Controller
public class UserController {
/**
* 上传文件
*/
@RequestMapping("/user")
public String getFile(MultipartFile file, Model model) throws Exception{
//
要判断file不为null的情况下...否则可能报空指针异常- //1.设置文件上传路径
String upload_path = "D:\\myDownload\\pictures\\";//最后的"\\"为了加上后缀.xxx
//2.获取文件名
String originalFilename = file.getOriginalFilename();
//3.获取后缀名(.xxx)
String pointName = originalFilename.substring(originalFilename.indexOf("."));
//新名字
String newName = UUID.randomUUID().toString()+pointName;
//4.创建本地文件
File newFile = new File(upload_path+newName);
//5.将内存中的数据写入磁盘
file.transferTo(newFile);
model.addAttribute("model", newName);
return "fileLoad";
}
}
4.跳转到fileLoad.jsp页面,回显图片
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
- ...
- <body>
- <!-- pic是配置的虚拟路径:详情见tomcat虚拟路径的配置 -->
- <!-- /开头代表绝对路径 pic --> D:\myDownload\pictures -->
- <img src="/pic/${model }">
- </body>
</html>