图片上传功能实现
java后端实现代码:
@ResponseBody
@RequestMapping("/home/updateInfoForm")
public Map<String, Object> update(MultipartFile imgFile, @RequestParam Map<String, Object> map, HttpServletRequest request) {
if (imgFile != null) {
// -----------------------------------------------------
//获取文件输入流
InputStream inputStream = null;
try {
inputStream = imgFile.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
//获取服务器存放图片的真实路径
String realPath = this.getRealPath("/upload", request);
//获取文件名称并且进行重命名
String originalFilename = imgFile.getOriginalFilename();
String newName = this.getNewName(originalFilename);
//在服务器上创建新文件
FileOutputStream fileOutputStream = null;
File file = new File(realPath, newName);
try {
fileOutputStream = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//文件复制
try {
IOUtils.copy(inputStream, fileOutputStream);
} catch (IOException e) {
e.printStackTrace();
}
//将路径保存到map数据库中
map.put("avatar", "upload/" + newName);
//-----------------------------------------------------------------
}
HttpSession session = request.getSession();
User user_model = (User) session.getAttribute("_USER_MODEL");
int id = user_model.getId();
map.put("id", id);
int i = userService.updateInfo(map);
System.out.println("i的值:" + i);
if (i > 0) {
User userAfterUpdate = userService.getUserById(id);
session.setAttribute("_USER_MODEL", userAfterUpdate);
map.put("success", true);
} else {
map.put("message", "更新失败");
}
return map;
}
//传入一个文件夹的名称,获取它在服务器上的真实路经
private String getRealPath(String s, HttpServletRequest request) {
String realPath = request.getSession().getServletContext().getRealPath(s);
File file = new File(realPath);
if (!file.exists()) {
file.mkdir();
}
return realPath;
}
//防止文件重名,重命名
private String getNewName(String oldName) {
UUID uuid = UUID.randomUUID();
String newName = uuid + oldName.substring(oldName.lastIndexOf("."));
return newName;
}
}
jsp部分:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE>
<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>更新资料</title>
<%@ include file="include/styles.jsp" %>
</head>
<body>
<jsp:include page="include/header.jsp"/>
<div class="container">
<div class="row">
<div class="col-xs-9">
<div class="panel panel-default">
<div class="panel-heading">
更新资料
</div>
<div class="panel-body">
<c:if test="${!empty _USER_MODEL.avatar}">
<p class="text-center">
<img src="${_USER_MODEL.avatar}" width="80px" height="80px" style="border-radius: 40px;">
</p>
</c:if>
<form class="form-horizontal" id="infoForm" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="imgFile" class="col-sm-2 control-label">头像</label>
<div class="col-sm-10">
<input type="file" class="form-control" id="imgFile" placeholder="" name="imgFile">
</div>
</div>
<div class="form-group">
<label for="email" class="col-sm-2 control-label">邮箱地址</label>
<div class="col-sm-10">
<input type="email" id="email" class="form-control" value="${_USER_MODEL.email }"
readonly="readonly">
</div>
</div>
<div class="form-group">
<label for="userName" class="col-sm-2 control-label">姓名</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="userName" id="userName"
placeholder="姓名,大名" value="${_USER_MODEL.userName}">
</div>
</div>
<div class="form-group">
<label for="nickName" class="col-sm-2 control-label">昵称</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="nickName" id="nickName"
placeholder="昵称,小名" value="${_USER_MODEL.nickName}">
</div>
</div>
<div class="form-group">
<label for="age" class="col-sm-2 control-label">年龄</label>
<div class="col-sm-10">
<input type="number" class="form-control" name="age" id="age" placeholder="年龄"
value="${_USER_MODEL.age}">
</div>
</div>
<div class="form-group">
<label for="introduction" class="col-sm-2 control-label">个人介绍</label>
<div class="col-sm-10">
<textarea class="form-control" name="introduction"
id="introduction">${_USER_MODEL.introduction}</textarea>
</div>
</div>
<div class="col-sm-10 col-sm-offset-2 text-right">
<button type="submit" class="btn btn-default">更新信息</button>
</div>
</form>
</div>
</div>
</div>
<div class="col-xs-3">
<jsp:include page="include/right.jsp"></jsp:include>
</div>
</div>
</div>
<%@ include file="include/scripts.jsp" %>
<script>
var fileFlag = false;
$(function () {
$("#imgFile").blur(function (){
$("#imgFile").each(function(){
console.log($(this).val())
if($(this).val()!="") {
fileFlag = true;
}else{
fileFlag = false;
}
});
})
$('#infoForm').validate({
submitHandler: function (form) {
if (fileFlag) {
//ajax提交
$(form).ajaxSubmit({
url: 'home/updateInfoForm.action',
method: 'post',
// dataType: 'json',
success: function (data) {
//响应结果
if (data.success) {
alert('修改信息成功');
location.reload();
} else {
alert('信息修改失败:' + data.message);
}
}
});
}else{
$.post('home/updateInfoForm.action', $(form).serialize(), function (data) {
if (data.success) {
alert('修改信息成功');
location.reload();
} else {
alert('信息修改失败:' + data.message);
}
});
}
},
rules: {
userName: {
required: true
},
nickName: {
required: true
},
age: {
required: true
}/*,
imgFile: {
required: true
}*/
}
});
});
</script>
</body>
</html>