图片上传预览并动态修改
最近因为工作原因,需要实现前端上传图片预览,不走服务器并且要求能一次上传多张。且因为后台已经有自己的存储图片接口,不能使用图片的base64码,需要用form表单上传,并要求能动态修改。在此要求下,我和产品经过了“友chun好qiang协she商zhan”,终于打消了他一次上传多张的念头(难以实现),一次只能选择一张!
本次功能的实现调用了FileReader接口,若要了解FileReader,请自行查看API。
现将代码简化,服务劳苦大众,话不多说,上代码:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<title>上传图片</title>
<style type="text/css">
.img_content{
width: 50%;
margin-top: 10px;
margin-right: 5px;
float: left;
border-radius: 8px;
position: relative;
overflow: hidden;
}
.img_content img{
width: 100%;
height: auto;
}
.img_remove{
height: 30px;
width: 100%;
background: rgba(0,0,0,.5);
position: absolute;
top: 0;
right:0;
display: inline-block;
}
.icon_remove_white{
width: 20px;
height: 20px;
float: right;
display: inline-block;
position: relative;
}
.icon_remove_white:before{
content: '';
width: 16px;
height: 2px;
background: #fff;
display: inline-block;
position: absolute;
top: 8px;
left: 0;
transform: rotate(-45deg);
}
.icon_remove_white:after{
content: '';
width: 16px;
height: 2px;
background: #fff;
display: inline-block;
position: absolute;
top: 8px;
left: 0;
transform: rotate(45deg);
}
</style>
</head>
<body>
<form action="">
<div class="upload_photos">
<input name="imagePath" type="file" id="uploadInput_1" data-id = "1" value = ""accept="image/png, image/jpeg, image/gif, image/jpg">
</div>
</form>
<div class="mt_5 clear" id="uploadImg"></div>
<script type="text/javascript" src = "jquery-3.1.1.min.js"></script>
<script type="text/javascript">
//上传附件资料照片
function UpLoadImg(file,id) {
var reader = new FileReader();
reader.onload = function (e) {
var dataURL = e.target.result,
img = new Image();
img.src = dataURL;
var html = document.createElement('div');
html.id = id;//设置添加的图片容器id
html.className = "img_content";
html.innerHTML = '<div class="img_remove">'+
'<div class="icon_remove_white">'+
'</div></div>';
$(html).append(img);
$('#uploadImg').append(html);//将图片添加进预览容器
};
reader.readAsDataURL(file);
}
//点击相机按钮后调用手机相册、文件夹、照相机
$('body').on('change','[name="imagePath"]',function(){
var $this = $(this);
data_id = parseInt($this.attr('data-id')),
file = this.files[0];
if(file){
UpLoadImg(file,data_id);
};
//每次上传照片后,动态添加下一个上传file
var next_file = $this.clone(true);
next_file[0].id = 'uploadInput_'+ (data_id + 1);//设置上传file的id
next_file.attr('data-id',data_id+1);//设置data-id
$this.hide();//隐藏上一个file
$this.parent().append(next_file);//添加file
});
//删除上传的照片
$('body').on('click','.icon_remove_white',function(){
var $this = $(this);
var remove_dom = $this.parents('.img_content'),//要删除的图片容器
id = remove_dom[0].id;//要删除的input的id(uploadInput_)后缀
$('#uploadInput_' + id).remove();//删除file
remove_dom.remove();//删除图片
});
</script>
</body>
</html>
浙公网安备 33010602011771号