前端HTML代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
.picture-container {
position: relative;
margin: 15px;
display: flex;
flex-direction: column;
width: 180px;
text-align: center;
}
.picture-echo {
position: absolute;
top: 0;
left: 0;
z-index: 1;
}
.echo-img {
width: 180px;
height: 120px;
margin: 0;
}
.picture-wrap {
width: 180px;
height: 120px;
position: relative;
box-sizing: border-box;
border: 1px solid #cfdadd;
}
.input-upload-file {
position: absolute;
width: 180px;
height: 120px;
top: 0;
left: 0;
cursor: pointer;
z-index: 3;
opacity: 0;
}
.upload-div {
width: 180px;
height: 120px;
position: absolute;
top: 0;
opacity: 0;
z-index: 3;
cursor: pointer;
}
</style>
</head>
<body>
<div class="picture-container">
<div class="picture-echo" id="echoImgWrap" style="display: none;">
</div>
<div class="picture-wrap wrap">
<input id="idCardFront" class="input-upload-file" type="file"
accept="image/jpeg, image/jpg, image/png" />
</div>
<div>
<button class="btn btn-rounded btn-primary" id="upload">点击上传</button>
</div>
</div>
</body>
jquery
<script src="user/js/vendor/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$(function(){
//获取到input对象
var idCardFront=$("#idCardFront");
//在显示框中添加一个img标签用来显示图片
$("#echoImgWrap").append($("<img id='show' style='height: 120px;'>"));
//给input对象绑定一个change事件
idCardFront.bind('change',function(){
//实例化一个FormData对象
var fordate=new FormData();
//将文件转化成二进制流
var fils=$("#idCardFront").get(0).files[0];
//将文件添加到formdata对象中
fordate.append('pic',fils);
//获取到文件路径
var srcc=window.URL.createObjectURL(fils);
//给img标签添加src属性,使图片回显
$("#show").attr({'src':srcc,'width':180+'px'});
$("#echoImgWrap").css("display","block");
//点击上传图片
$("#upload").click(function () {
$.ajax({
url: "http://127.0.0.1:8082/admin/upload",
type: "POST",
data: fordate,
processData : false,
contentType : false,
success: function(data){
console.log(data);
}
});
})
});
});
</script>
controller
@RestController
@RequestMapping("/admin")
public class AdminController {
@PostMapping(value = "/upload")
private String upload(MultipartFile pic){
//写自己的业务
return null;
}
}