JS、JQ实现图片上传
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="./jquery-3.4.1.min.js"></script>
<title>Document</title>
<style>
.img-cont{
width:1030px;
height:300px;
border:2px solid #317ef3;
margin:20px auto;
}
.img-cont>div{
width:180px;
height:260px;
border:1px solid #777;
float:left;
margin:20px 0 0 20px;
}
.img-cont>div>div{
width:180px;
height:220px;
border:1px solid red;
}
.img-cont>div>a{
width:60px;
height:30px;
border-radius:4px;
line-height: 30px;
text-align: center;
color:#fff;
display: block;
background: #317ef3;
margin:5px 0 0 0px;
cursor: pointer;
}
.hide{
display: none !important;
}
</style>
</head>
<body>
<center>
<!-- 图片框 -->
<form>
<input type="file" onchange='PreviewImage(this)' />
</form>
<!-- 图片展示 -->
<div class="img-cont"></div>
</center>
</body>
<script>
var id="1";
function PreviewImage(imgFile) {
let numCount = $('.img-cont').children().length;
if(numCount >= 6){
alert("最多可以上传6张图片");
return;
};
var pattern = /(\.*.jpg$)|(\.*.png$)|(\.*.jpeg$)/;
if(!pattern.test(imgFile.value)) {
alert("系统仅支持jpg/jpeg/png格式的照片!");
return;
};
var file = imgFile.files[0];
var formData = new FormData();
formData.append("file", file, file.name);
$.ajax({
url: '/rest/personal/up',
dataType: 'json',
type: "POST",
cache: false,
contentType: false,
processData: false,
data: formData,
async: true,
success: function (data) {
materImage.push(data.data);
var id= Math.random();
var path;
id+=1;
$(".img-cont").append("<div><div id='"+id+"'><img src='' /></div><a class='hide delete-btn'>删除</a></div>");
if(document.all){
imgFile.select();
path = document.selection.createRange().text;
document.getElementById(id).innerHTML="";
document.getElementById(id).style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',sizingMethod='scale',src=\"" + path + "\")";
}else{
path = URL.createObjectURL(imgFile.files[0]);
document.getElementById(id).innerHTML = "<img src='"+path+"' width='175' height='220' />";
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.error(errorThrown);
if (XMLHttpRequest.responseText.indexOf("400") > -1) {
alert("网络不给力,请稍后再试!");
} else {
alert("网络不给力,请稍后再试!");
}
}
});
}
function resetForm(imgFile){
$(imgFile).parent()[0].reset();
}
$(".img-cont").off("mouseenter","div").on("mouseenter","div",function(){
var that=this;
var dom=$(that).children("a");
dom.removeClass("hide");
dom.off("click");
dom.on("click",function(){
dom.parent().remove();
});
}).off("mouseleave","div").on("mouseleave","div",function(){
var that=this;
$(that).children("a").addClass("hide");
})
</script>
</html>