需求:点击头像上传图片进行局部刷新(将上传的图片显示为头像)
需要使用的工具:
①ajax
②fileupload
主要代码:
jsp
<%--
Created by IntelliJ IDEA.
User: TianXinKun
Date: 2021/9/7
Time: 14:29
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>lg上传</title>
<link rel="stylesheet" href="css/bootstrap.css" type="text/css">
<link rel="stylesheet" href="css/lg.css" type="text/css">
</head>
<script type="text/javascript">
function onclick1() {
var request = new XMLHttpRequest();
request.open("post", "/lg.do", true);
var dataFrame = new FormData();
dataFrame.append("image", document.getElementById("test2").files[0])
request.onload = function () {
if (request.responseText != null) {
alert("成功")
document.getElementById("test1").style.backgroundImage = "url('/imags/" + request.responseText + "')";
}
}
request.send(dataFrame);
}
</script>
<body>
<div class="container">
<div class="row">
<div class="col-auto" style="height: 100px;">
<a href="#" class="file" style="width: 100px" id="test1">
<input type="file" name="imag" id="test2" onchange="onclick1()">
</a>
</div>
</div>
</div>
</body>
</html>
@RequestMapping
@RequestMapping(value = "/lg.do",method = RequestMethod.POST)
public void lg(@RequestParam("image")CommonsMultipartFile file, Writer writer, HttpServletRequest request){
String originalFilename = file.getOriginalFilename();
System.out.println(originalFilename);
String path = request.getRealPath("/imags/");
File image = new File(path,originalFilename);
try {
file.transferTo(image);
writer.write(originalFilename);
} catch (IOException e) {
e.printStackTrace();
}
}
css
.file {
position: relative;
display: inline-block;
background: url("/imags/用户.png") no-repeat;
background-size: contain;
height: 100%;
border: 1px solid #99D3F5;
border-radius: 4px;
padding: 4px 12px;
overflow: hidden;
color: #1E88C7;
text-decoration: none;
text-indent: 0;
line-height: 20px;
}
.file input {
position: absolute;
font-size: 100px;
right: 0;
top: 0;
opacity: 0;
width: 100%;
height: 100%;
}
.file:hover {
/*background: #AADFFD;*/
border-color: #78C3F3;
color: #004974;
text-decoration: none;
}
主要难点:
①上传图片位置:不是编写路径是Tomcat运行时的资源真实路径
②/image/文件夹至少要有一个图片,空文件夹Tomcat不会“生成”
当出现imags才不会报空指针!!