使用js完成页面上的上传图片预览

一 单张图片预览

1,首先我们要设计一个页面,如image.jsp(随你,这里是这个jsp页面)

<body >
<div>
<input type="file" id="picture" name="picture"/>
</div>
<div>
<img alt="图片预览" src="" id="showHeadImg">
</div>
</body>

<script type="text/javascript">
$(function(){
$("#picture").bind("change",function() {
var url = null;
if (window.createObjectURL != undefined) {
url = window.createObjectURL(this.files[0]);
} else if (window.URL != undefined) {
url = window.URL.createObjectURL(this.files[0]);
} else if (window.webkitURL != undefined) {
url = window.webkitURL.createObjectURL(this.files[0]);
}
console.log(this.files[0]);
$("#showHeadImg").attr("src",url);
});
});
</script>

页面代码如上:效果图如下:

 

当然这里面图片的大小是可以调整的,这个就留给读者了,嘿嘿嘿!

 

二 多张图片预览

1,同样你也需要个界面,就还有上面的界面好了

界面代码如下:

js:

$("#photo").bind("change",function(){
var url = null;
if (window.createObjectURL != undefined) {
url = window.createObjectURL(this.files[0]);
} else if (window.URL != undefined) {
url = window.URL.createObjectURL(this.files[0]);
} else if (window.webkitURL != undefined) {
url = window.webkitURL.createObjectURL(this.files[0]);
}
var content = '<div>'
+ '<img src="' + url + '" style="width:251px;height:250px"></div>'
+ '<div id="delPhoto"><span">删除</span></div>'
+ '';
$("#photos").append(content);
$("#delPhoto").click(function() {
$(this).parent().remove();
});
})

 页面:

<div>
<input type="file" id="photo" name="photo"/>
</div>

<div>
<ul id="photos">

</ul>
</div>

效果如图:

页面样式非常简陋,不喜勿喷啊!

 

posted on 2016-10-08 16:50  罗苏  阅读(542)  评论(0编辑  收藏  举报