主要步骤:
首先需要导入两个操作所需的Jar包:
commons-fileupload-1.2.2.jar
commons-io-2.4.jar
1,在form表单设置属性:
<form action="${basePath}upload" method="post" enctype="multipart/form-data">
<label>头 像</label><input type="file" name="file"/><br/>
<input type="submit" value="提 交"/>
</form>
2, 配置文件里配置一个MultipartResolver解析器
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8" />
<!-- 最大内存大小 -->
<property name="maxInMemorySize" value="10240" />
<!-- 最大文件大小,-1为不限制大小 -->
<property name="maxUploadSize" value="-1" />
</bean>
3,在相应的控制器设置接收参数类型为MutilpartFile:
private StringfileUpload(@RequestParam(value="file",required=false)
MultipartFile file,HttpServletRequest request) throws Exception{
4,在Controller里面定义图片保存路径
String pathRoot = request.getSession().getServletContext().getRealPath("");
path="/imagies/1/"+uuid+"."+imageName;
File file2=new File(pathRoot+path);
5,将文件保存到定义的路径下
file.transferTo(file2);
controller完整代码如下:
@Controller
public class uploadController {
@RequestMapping(value="/upload",method=RequestMethod.POST)
private String fildUpload(@RequestParam(value="file",required=false) MultipartFile file,
HttpServletRequest request)throws Exception{
//获得物理路径webapp所在路径
String pathRoot = request.getSession().
getServletContext().getRealPath(" ");
String path="";
if(!file.isEmpty()){
//生成uuid作为文件名称,防止直接使用名字出现重复
String uuid = UUID.randomUUID().toString().replaceAll("-","");
//获得文件类型 返回image/后缀
String contentType=file.getContentType();
//获得文件后缀名称
String imageName=contentType.substring(contentType.indexOf("/")+1);
//把文件保存至本地自定义目录下:一般做法会把上传文件保存在服务器下的项 目内,但是这样的上传文件会在你项重新发布项目后消失;
// File.separator为斜杠;
String localpath="D:"+File.separator+"imagies"
+File.separator+uuid+"."+imageName;
path="/imagies/1/"+uuid+"."+imageName;
File file2=new File(pathRoot+path);
//把图片存进指定目录;
file.transferTo(file2);
}
request.setAttribute("path", path);
return "succes";
}
}
显示已上传的图片代码:
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
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>
<base href="<%=basePath%>">
<title>My JSP 'succes.jsp' starting page</title>
</head>
<body>
<img src="${basePath}${path}" >
${basePath}${path}
</body>
</html>