1.导入需要的jar包,或者在maven中引入依赖
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
2.在springmvc.xml 文件中配置文件上传解析器
<!-- 文件上传解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 上传文件最大的大小 -->
<property name="maxUploadSize" value="41300260"></property>
<!-- 字符编码 -->
<property name="defaultEncoding" value="utf-8"></property>
</bean>
3.前端的的表单提交类型"multipart/form-data"
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>上传图片</title>
<link rel="stylesheet" href="http://www.jq22.com/jquery/bootstrap-3.3.4.css" />
<script src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://www.jq22.com/jquery/bootstrap-3.3.4.js"></script>
</head>
<body>
<div style="width: 600px;height: auto;background-color: aliceblue;margin: 5% auto auto auto;">
<form action="uploadBook" method="post" enctype="multipart/form-data" >
<div class="col-sm-offset-4 col-sm-10">
<h2>书籍信息录入</h2>
</div>
<div class="form-group" >
<label >书名</label>
<input type="text" class="form-control info" name="sname" id="sname" onfocus="showTips('sname','请输入书名')"
onblur="checkFormat('sname','书名不能为空')"><span id="snamespan"></span>
</div>
<div class="form-group">
<label >价格</label>
<input type="number" class="form-control" name="sprice" placeholder="请输入价格" >
</div>
<div class="form-group">
<label >所属类型</label>
<select class="form-control" id="type" name="type">
<option value="">请选择</option>
<option value="1">计算机</option>
<option value="2">经济管理</option>
<option value="3">励志言情</option>
<option value="4">育儿家教</option>
<option value="5">绘画摄影</option>
<option value="0">其他</option>
</select>
</div>
<div class="form-group">
<label >图片</label>
<input type="file" id="bimg" name="bimg">
</div>
<div class="col-sm-offset-4 col-sm-10">
<button type="submit" class="btn btn-default">添加书籍</button>
</div>
</form>
</div>
</body>
<script>
/*聚焦时对input内容格式进行提示*/
function showTips(id,info){
document.getElementById(id+"span").innerHTML="<font color='#444359'>"+info+"</font>";
}
/*离焦时input内容进行检测*/
function checkFormat(id,info){
var novals = document.getElementById(id).value;
if(novals ==""){
document.getElementById(id+"span").innerHTML="<font color='red'>"+info+"</font>";
}else{
document.getElementById(id+"span").innerHTML="";
}
}
</script>
</html>
实际页面如下:
4.获取表单里的数据,注意文件的类型是MultipartFile ,普通表达参数的类型是MultipartHttpServletRequest ,获取表单值的方法是value=getParameter(key);
@ResponseBody
@RequestMapping(value = "uploadBook",method = RequestMethod.POST)
public ReturnData addBookInfo(@RequestParam("bimg")MultipartFile file, MultipartHttpServletRequest request) throws IOException {
if(file != null){
String path=null;// 文件路径
String type = null;//文件类型
String fileName=file.getOriginalFilename();// 文件原名
logger.info("上传的源文件名称:"+fileName);
type=fileName.indexOf(".")!=-1?fileName.substring(fileName.lastIndexOf(".")+1, fileName.length()):null;
if(type != null){
if("GIF".equals(type.toUpperCase())||"PNG".equals(type.toUpperCase())||"JPG".equals(type.toUpperCase())){
// 项目在容器中实际发布运行的根路径
String realPath=request.getSession().getServletContext().getRealPath("/");
// 自定义的文件名称
String trueFileName=String.valueOf(System.currentTimeMillis())+fileName;
// 设置存放图片文件的路径
path=realPath+"upload/"+trueFileName;
logger.info("图片存储的路径是:"+path);
// 转存文件到指定的路径
file.transferTo(new File(path));
String title=request.getParameter("sname");
String bsprice=request.getParameter("sprice");
String btype=request.getParameter("type");
Books book = new Books();
book.setBimg(trueFileName);
book.setType(btype);
book.setBprice(bsprice);
book.setBname(title);
int rows =userService.addBook(book);
if(rows>0){
logger.info("数据填进数据库");
}
}else {
return ReturnData.error(1,"文件类型错误");
}
}else{
return ReturnData.error(2,"文件类型为空");
}
}else{
return ReturnData.error(3,"没有找到相对应的文件");
}
return ReturnData.ok("书籍信息添加成功");
}
5.总结,在获取普通表单参数的时候,使用HttpServletRequest的getAttribute(key)方法,拿不到普通参数的值,后来在更换为MultipartHttpServletRequest,在调试的时候,发现multipartParametet,就试着用getParameter(key)获取普通参数值.