javascript实现即时显示上传缩略图

 
更多

javascript实现即时显示上传缩略图,记录在此,以备后用!注意这里仅仅通过javascript实现了这样一个效果,即选中上传文件之后只是通过js调用图片存储在本地的文件地址,然后显示出来。这个过程中没有上传图片到服务器的操作,这个和 uploadify 这个插件不一样,uploadify 上传插件是在选择文件的过程中就已经将图片上传到服务器了,实时显示的文件也是服务器上的文件。

需要了解 uploadify 这个插件的朋友可以参照本站文章:

Uploadify(JQuery上传插件)使用配置详解

下面是本示例的效果图:

javascript实现即时显示上传缩略图

以下是具体的代码:

<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>
打赏

本文固定链接: https://www.cxy163.net/archives/3928 | 绝缘体

该日志由 绝缘体.. 于 2013年08月01日 发表在 未分类 分类下, 你可以发表评论,并在保留原文地址及作者的情况下引用到你的网站或博客。
原创文章转载请注明: javascript实现即时显示上传缩略图 | 绝缘体
关键字: , , , ,

javascript实现即时显示上传缩略图:等您坐沙发呢!

发表评论


快捷键:Ctrl+Enter