图片上传有2个选择:
1:本地确认好后把图片上传到服务器
2:只要input改变就ajax异步请求将图片传到服务器。然后服务器返回上传的这个图片的链接地址。然后再再页面上展示出来。这样做的好处是提高兼容性。可以不用考虑IE兼容等等
这里只展示第一种上传方式的预览
html代码:
<div class="up_img mar_t10 mar_l60 f_l over_h">
<ul class="new_img f_l">
</ul>
<div class="up_push f_l">
<input id="file" type="file" />
<i class="icon icon-plus"></i>
<p>上传图片</p>
</div>
</div>
css代码
.up_img{
max-width:330px;
height: 100px;
overflow: hidden;
}
.new_img .preview{
float: left;
width: 100px;
height: 100px;
margin-right: 10px;
box-sizing: border-box;
border: 1px solid #ccc;
}
.up_push{
box-sizing: border-box;
border: 1px solid #ccc;
width: 100px;
height: 100px;
background: #F1F1F1;
text-align: center;
padding-top: 25px;
cursor:pointer ;
position: relative;
}
.up_push i{
color: #aaa;
font-size:30px;
}
#file{
width:100%;
height:100%;
position: absolute;
left: 0;
top: 0;
z-index: 1;
filter:alpha(opacity=0);
-moz-opacity:.0;
opacity:0.0;
cursor:pointer;
}
upimg:function(){
//上传图片
$('#file').on('change',function(){
var MAXWIDTH = 100;
var MAXHEIGHT = 100;
$('.new_img').append('<li class="preview"><img src=""/></li>')
var div = $('.preview:last');
if(file.files && file.files[0]) {
var img = $('.preview:last>img')[0];
img.onload = function() {
var rect = clacImgZoomParam(MAXWIDTH, MAXHEIGHT, img.offsetWidth, img.offsetHeight);
img.width = rect.width;
img.height = rect.height;
img.style.marginLeft = rect.left+'px';
img.style.marginTop = rect.top + 'px';
}
var reader = new FileReader();
reader.onload = function(evt) {
img.src = evt.target.result;
}
reader.readAsDataURL(file.files[0]);
}
})
//规定图片的显示高宽和上左间距
function clacImgZoomParam(maxWidth, maxHeight, width, height) {
var param = {
top: 0,
left: 0,
width: width,
height: height
};
rateWidth = width / maxWidth;
rateHeight = height / maxHeight;
if(rateWidth > rateHeight) {
param.width = maxWidth;
param.height = Math.round(height / rateWidth);
param.left = 0;
param.top = Math.round((maxHeight - param.height) / 2);
} else {
param.width = Math.round(width / rateHeight);
param.height = maxHeight;
param.left = Math.round((maxWidth - param.width) / 2);
param.top = 0;
}
return param;
}
}