JavaScrip实现上传图片预览

出处:  http://hi.baidu.com/zml525/blog/item/9427606391edde610c33fa9d.html

<script language="javascript">
function showimg(){
document.all.imgview.innerHTML="<img src='"+document.all.myimg.value+"'>";
}
</script>

<span id="imgview"></span>

<input type="file" id="myimg" onchange="showimg()">

如何图片太大或太小了可以进行比例的缩小或放大

如下面:

<html>
<head>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data" name="form1">
<input name="attach" type="file" onchange="javascript:ShowImg(this.value);" onKeyDown="javascript:return(false);" size="20">
<script language="JavaScript">
function ShowImg(src)
{
document.getElementById("imgDiv").innerHTML="图片预览:<br><img id='imgObj' onerror='javascript:GetError()' onload='javascript:GetSize()' src='file:///" + src + "'>";
}
function GetSize()
{
var width,height;
var imgObj=document.getElementById("imgObj");
width=imgObj.width;
height=imgObj.height;
document.getElementById("err_msg").innerHTML="图片大小(宽×高):<font color=red>" + width + "×" + height + "</font>";
if(width>164){
imgObj.width=164;
imgObj.height=imgObj.height/(imgObj.width/164);
}
}
function GetError()
{
document.getElementById("err_msg").innerHTML="图片大小(宽×高):<font color=red>NaN</font>";
document.getElementById("imgDiv").innerHTML="";
document.getElementById("err_msg").innerHTML="图片文件不存在或格式错误!"
}
</script>
<div id="imgDiv" align="center"></div>
<div id="err_msg" align="center"></div>
</form>
</body>
</html>

你可能感兴趣的:(JavaScrip实现上传图片预览)