1. 摘要
Spring MVC为文件上传提供了最直接的支持,这种支持是通过即插即用的MultipartResolve实现的。Spring使用Jakarta Commons FileUpload技术实现了一个MultipartResolver实现类:CommonsMultipartResolver。
下面将具体讲解Spring MVC实现文件上传的具体步骤。
2. 添加Jar包
Spring MVC文件上传,需要添加如下两个jar包:
- commons-fileupload-1.2.2.jar;
- commons-io-2.0.1.jar
3. 配置CommonsMultipartResolver
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--上传文件的最大大小-->
<property name="maxUploadSize" value="17367648787"></property>
<!-- 上传文件的编码 -->
<property name="defaultEncoding" value="UTF-8"></property>
</bean>
说明:
-
defaultEncoding="UTF-8":这里设置默认的文件编码为UTF-8,必须与用户JSP的默认编码一致;
- maxUploadSize="5000000":指定文件上传大小,单位为字节;
4. 控制层代码
@RequestMapping(value = "", method = RequestMethod.GET)
public String uploadPage(@RequestParam(required = false, defaultValue = "1") Integer pageNo,
@RequestParam(required = false, defaultValue = "30") Integer pageSize, Model model) {
Site site = CmsUtils.getSite(Site.defaultSiteId());
model.addAttribute("site", site);
return "modules/cms/front/themes/" + site.getTheme() + "/frontUpload";
}
@RequestMapping(value = "upload.action", method = RequestMethod.GET)
public String uploadPageSuccess(@RequestParam(required = false, defaultValue = "1") Integer pageNo,
@RequestParam(required = false, defaultValue = "30") Integer pageSize, Model model) {
Site site = CmsUtils.getSite(Site.defaultSiteId());
model.addAttribute("site", site);
return "modules/cms/front/themes/" + site.getTheme() + "/frontUploadSuccess";
}
@RequestMapping(value = "/upload")
public String updateThumb(@RequestParam("name") String name, @RequestParam("file") MultipartFile file,
HttpServletRequest request, ModelMap model) throws Exception {
if (!file.isEmpty()) {
// 保存文件-方式1 --测试过,可以用,必须先创建相应目录
// file.transferTo(new File("d:/"+file.getOriginalFilename()));
// 保存文件-方式2
String path = request.getSession().getServletContext().getRealPath("upload");
String fileName = file.getOriginalFilename();
File targetFile = new File(path, fileName);
// 目录不存在,则创建目录
if (!targetFile.exists()) {
targetFile.mkdirs();
}
// 保存
try {
file.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
model.addAttribute("fileUrl", request.getContextPath() + "/upload/" + fileName);
System.out.println("上传成功");
return "redirect:"+Global.getFrontPath()+"/upload/upload.action";
} else {
return "fail";
}
}
前台请求:http://localhost:8080/askdcrm/f/upload 时,返回frontUpload.jsp界面,如下:
5. 文件上传JSP
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="/WEB-INF/views/modules/cms/front/include/taglib.jsp"%>
<html>
<head>
<title>请上传用户头像</title>
<link href="${ctxStatic}/frontUpload/css/bootstrap.min.css" rel="stylesheet">
<link href="${ctxStatic}/frontUpload/css/bootstrap-fileinput.css" rel="stylesheet">
<script src="${ctxStatic}/frontUpload/js/jquery.min.js"></script>
<script src="${ctxStatic}/frontUpload/js/bootstrap-fileinput.js"></script>
</head>
<body>
<h1>请选择上传的图片</h1>
<form method="post" action="<c:url value="/f/upload/upload.action"/>"
enctype="multipart/form-data">
<input type="hidden" name="name" />
<div class="form-group" id="uploadForm" enctype='multipart/form-data'>
<div class="h4">图片预览</div>
<div class="fileinput fileinput-new" data-provides="fileinput" id="exampleInputUpload">
<div class="fileinput-new thumbnail" style="width: 200px;height: auto;max-height:150px;">
<img id='picImg' style="width: 100%;height: auto;max-height: 140px;" src="${ctxStatic}/frontUpload/images/noimage.png" alt="" />
</div>
<div class="fileinput-preview fileinput-exists thumbnail" style="max-width: 200px; max-height: 150px;"></div>
<div>
<span class="btn btn-primary btn-file">
<span class="fileinput-new">选择文件</span>
<span class="fileinput-exists">换一张</span>
<input type="file" name="file" id="picID" accept="image/gif,image/jpeg,image/x-png"/>
</span>
<a href="javascript:;" class="btn btn-warning fileinput-exists" data-dismiss="fileinput">移除</a>
</div>
</div>
</div>
<button type="submit" id="uploadSubmit" class="btn btn-info">提交</button>
</form>
</body>
</html>