Aug
01
2013
javascript实现即时显示上传缩略图
作者:
绝缘体.. 发布:
2013-08-01 06:34 分类:
未分类 阅读:
抢沙发
javascript实现即时显示上传缩略图,记录在此,以备后用!注意这里仅仅通过javascript实现了这样一个效果,即选中上传文件之后只是通过js调用图片存储在本地的文件地址,然后显示出来。这个过程中没有上传图片到服务器的操作,这个和 uploadify 这个插件不一样,uploadify 上传插件是在选择文件的过程中就已经将图片上传到服务器了,实时显示的文件也是服务器上的文件。
需要了解 uploadify 这个插件的朋友可以参照本站文章:
Uploadify(JQuery上传插件)使用配置详解
下面是本示例的效果图:

以下是具体的代码:
<html xmlns="http://www.phpernote.com/javascript-function/61.html">
<head>
<meta content="text/html; charset=utf-8" http-equiv=content-type>
<meta name=author content="Laruence(www.laruence.com)">
<title>即时显示上传缩略图</title>
</head>
<body style="text-align:center;">
<div>
<div style="width:200px; height:200px; border:1px solid #666;"><img id="img" style="visibility:hidden;" height="100%" width="100%"></div>
<div style="margin-top:8px;"><input id="file" type="file" onChange="preivew(this,'img');"></div>
</div>
<script language="javascript" type="text/javascript">
var allowExt=['jpg', 'gif', 'bmp', 'png', 'jpeg'];
var preivew=function(file, container){
try{
var pic=new Picture(file, document.getElementById(container));
}catch(e){
alert(e);
}
}
//缩略图类定义
var Picture=function(file, container){
var height=0,
widht =0,
ext='',
size=0,
name='',
path='';
var self=this;
if(file){
name=file.value;
if(window.navigator.userAgent.indexOf("MSIE")>=1){
file.select();
path=document.selection.createRange().text;
}else if(window.navigator.userAgent.indexOf("Firefox")>=1){
if(file.files){
path=file.files.item(0).getAsDataURL();
}else{
path=file.value;
}
}
}else{
throw '无效的文件';
}
ext=name.substr(name.lastIndexOf("."), name.length);
if(container.tagName.toLowerCase()!='img'){
throw '不是一个有效的图片容器';
container.visibility='hidden';
}
container.src=path;
container.alt=name;
container.style.visibility='visible';
height=container.height;
widht=container.widht;
size=container.fileSize;
this.get=function(name){
return self[name];
}
this.isValid=function(){
if(allowExt.indexOf(self.ext)!==-1){
throw '不允许上传该文件类型';
return false;
}
}
}
</script>
</body>
</html>
微信扫一扫,打赏作者吧~