接上次<html原生表单>
html
<div id='img_list' >
<div id='close'>
//放一个svg的icon,关闭的❌
</div>
</div>
<div class="input-file-box">
<div class='icon'>
//放一个svg的icon,+表示上传,用来改变input的样式
</div>
<div id='upload-box'>
<input accept="image/*" name='upload' id='upload' type='file' onchange='uploadOnchange()'/>
</div>
js
function uploadOnchange(){
let upload=document.getElementById('upload')
console.log(upload)
let file=upload.files[0];
let name=file.name;
var reader= new FileReader();
var image = new Image();
reader.readAsDataURL(file);
reader.onload=function(){
image.src = this.result;
//预览
document.getElementById('img_list').append(image)
//图片压缩
image.onload=()=>{
let comSrc=this.result
if(file.size>1024){
comSrc= compress(image)
}
// console.log('comSrc',comSrc)
//压缩完成存入数据库
$.ajax({
url:"http://localhost:8080/api/picture",
type:'POST',
data:JSON.stringify({img:comSrc,name}),
dataType: "json",
processData: false,
contentType: "application/json",
success:function(data){
//保存返回的图片url存入全局变量
imgUrlArr.push(data.url)
//更新input
document.getElementById("upload-box").innerHTML= `<input accept="image/*" name='upload' id='upload' type='file' onchange='uploadOnchange()' />`;
},
error:function(data){
}
})
}
}
}
压缩图片函数
let compress=function(image){
var height = image.height;
var width = image.width;
var canvas = document.createElement('canvas');
//height、 width 和图片实际的高、宽一致时,直接赋值canvas的宽高为上述宽高
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext('2d');
ctx.fillStyle = '#FFF';//绘制背景色
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
//0.5为压缩的质量比例,范围是0~1。
var imgBase = canvas.toDataURL("image/jpeg",0.5);
return imgBase
}
预览图片删除
let selectImg,index
$('#img_list').click(function(e){
if(e.target.tagName=='IMG'){
index=$('#img_list img').index(e.target)
$('#close').css('top',index*133+'px').show()
selectImg=e.target
}else{
$('#close').css('top','0px').hide()
imgUrlArr.splice(index,1)
console.log(imgUrlArr)
selectImg.remove()
}
})
css,主要改了h5图片上传的样式,还有预览图片的样式
/* 图片预览 */
#activity .info #img_list{
width:128px;
position:relative
}
#activity .info #close{
display:none;
position:absolute;
right:5px;
/* top:10px */
}
#activity .info #img_list>img{
width:128px;
height:128px;
display:block;
margin-bottom:5px;
}
#activity .info .input-file-box{
/* border: 1px solid gray; */
width: 64px;
height: 64px;
position: relative;
text-align: center;
border-radius: 8px;
}
#activity .info .input-file-box #upload{
opacity:0;
width: 100%;
height: 100%;
position:absolute;
top:0;
right:0;
bottom:0;
left:0;
cursor: pointer;
}
#activity .info .input-file-box>.icon{
position:absolute;
top:0;
right:0;
bottom:0;
left:0;
}
效果