很多项目都用文件长传功能,最近做一个项目用到上传图片功能,把自己实践基于SpringMVC上传图片的功能分享出来也是当作笔记,希望对大家有帮助;
1、首先在SpringMVC的配置文件dispatcherServlet-servlet.xml中加入文件解析器:
<!-- 文件解析器 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 上传文件最大值5M=5*1024*1024 -->
<property name="maxUploadSize" value="5242880"/>
</bean>
2、在form表单中加入 enctype="multipart/form-data",否则会报异常,表单中enctype="multipart/form-data"的意思是设置表单的MIME编码。默认情况,这个编码格式是application/x-www-form-urlencoded,不能用于文件上传;只有使用了multipart/form-data,才能完整的传递文件数据,进行下面的操作. enctype="multipart/form-data"是上传二进制数据;form里面的input的值以2进制的方式传过去。
3、前台直接贴代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="multipart/form-data; charset=UTF-8">
<%
pageContext.setAttribute("contextPath", request.getContextPath());
%>
<title>图片上传</title>
<script type="text/javascript" src="${contextPath}/static/jquery-2.2.4.min.js"></script>
</head>
<body>
<form action="${contextPath}/upload" method="post" enctype="multipart/form-data">
选择照片:<input type="file" name="imgfile"><br>
照片描述:<input type="text" name="describe"><br>
<input type="submit" value="上传"><br>
</form>
</body>
</html>
4、后台通过@RequestParam("imgfile") MultipartFile imgfile接收传过来的file
@RequestMapping("/upload")
public String fileUpload(Image image, HttpServletRequest request,
@RequestParam("imgfile") MultipartFile imgfile) throws IllegalStateException, IOException{
//获取图片名
String fileName = imgfile.getOriginalFilename();
//截取图片后缀
String suff = fileName.substring(fileName.lastIndexOf("."));
//判断是否是图片
if(!(suff.matches(".(jpg||gif||png)"))){ //不是个图片
System.err.println("您上传的不是图片!");
return "error";
}
if (imgfile != null && fileName != null && fileName.length() > 0) {
//新图片名
String newFileName = UUID.randomUUID() + suff;
//编辑路径
String localPath = "H:/image/homePage/";
//新图片
File newfile = new File(localPath + newFileName);
if (!newfile.exists()) {
//文件不存在时创建多个文件
newfile.mkdirs();
}
//将图片写入磁盘
imgfile.transferTo(newfile);
image.setImgPath(newFileName);
}
//调用service层方法
int n = imageService.addImage(image);
if (n > 0) {
System.out.println("插入图片成功");
}
return "success";
}