jsp页面
1.点击选择文件,添加文件
2.当改变状态是,触发函数subImg,提交表单数据至后台
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>图片更换测试</title>
<script src="${pageContext.request.contextPath}/js/jquery-1.8.3.js"></script>
<script src="${pageContext.request.contextPath}/js/jquery.form.js"></script>
<script>
function subImg() {
alert("执行ajax");
var options = {
type:'post',
url:'${pageContext.request.contextPath}/student/get.do',
dataType:'json',
success:function (resData) {
// 显示后台数据拿到图片地址
console.log(resData.imgUrl);
// 添加图片src地址
$("#pic").attr('src',resData.imgUrl);
$("#hiddenPic").val(resData.imgUrl);
}
};
//提交表单
$('#itemsForm').ajaxSubmit(options);
}
</script>
</head>
<body>
<form action="${pageContext.request.contextPath}/student/get.do" id="itemsForm" method="post">
<%-- 图片显示--%>
<img width="100px" height="100px" id="pic">
<%-- 图片上传入口--%>
<input type="file" name="headphoto" onchange="subImg()">
<%-- 图片地址保存入口--%>
<input type="hidden" id="picaddress">
<%-- 表单提交--%>
<input type="submit" value="提交">
</form>
</body>
</html>
Controller层
3.获取图片参数,存储文件(更改文件名)
4.返回文件路径,显示文件,将文件路径写入input框
5.点击更新,表单提交写入数据库
部分源码
@RequestMapping("get")
public void get(HttpServletRequest request,HttpServletResponse response) throws IOException { ;
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
//获取图片参数
MultipartFile headphoto = multipartRequest.getFile("headphoto");
//输出图片参数
System.out.println("图片参数"+headphoto);
//存放路径
String realPath = request.getServletContext().getRealPath("upload2");
System.out.println("文件存放路径"+realPath);
//判断是否存在文件 不存在则创建
File file = new File(realPath);
if (!file.exists()){
file.mkdir();
}
//获取文件的后缀名字
String originalFilename = headphoto.getOriginalFilename().split("\\.")[1];
//生成随机文件的名字
String s = UUID.randomUUID().toString()+"."+originalFilename;
//完整文件名
System.out.println("文件名为:"+s);
//完整路径文件名
String totalPath = realPath+"\\"+s;
//文件存入文件夹
FileCopyUtils.copy(headphoto.getInputStream(),new FileOutputStream(totalPath));
//返回数据给客户端
//完整路径名
String imgUrl = "http://localhost:8080/ssm_war_exploded/upload2/" + s;
String responseJson = "{\"imgUrl\":\"" + imgUrl + "\"}";
response.setHeader("content-type","text/json;charset=utf-8");
response.getWriter().write(responseJson);
}