Upload image preview JS script Input file image preview implementation example

  • 2020-03-30 04:10:43
  • OfStack

When doing a project in shenzhen, we need a user upload avatar preview function! I found a lot of them on the Internet, but I'm not satisfied with them. It's either flash, it's an Ajax upload that returns the image path, or it doesn't work at all. Fortunately, in this project before someone wrote a picture preview function, but also was turned out by me, here to make a record, convenient for their future use, but also convenient for other need friends!

The code is simple as follows:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>By : DragonDean</title>
<script type="text/javascript">
//Below is a preview for image upload
function setImagePreview(avalue) {
var docObj=document.getElementById("doc");

var imgObjPreview=document.getElementById("preview");
if(docObj.files &&docObj.files[0])
{
//Under firefox, set the img property directly
imgObjPreview.style.display = 'block';
imgObjPreview.style.width = '150px';
imgObjPreview.style.height = '180px'; 
//imgObjPreview.src = docObj.files[0].getAsDataURL();

//Firefox 7 + cannot be obtained in getAsDataURL () above
imgObjPreview.src = window.URL.createObjectURL(docObj.files[0]);
}
else
{
//Under IE, use a filter
docObj.select();
var imgSrc = document.selection.createRange().text;
var localImagId = document.getElementById("localImag");
//You must set the initial size
localImagId.style.width = "150px";
localImagId.style.height = "180px";
//Image abnormal capture, prevent users to modify the suffix to forge the image
try{
localImagId.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
localImagId.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc;
}
catch(e)
{
alert(" The format of the picture you uploaded is not correct, please choose again !");
return false;
}
imgObjPreview.style.display = 'none';
document.selection.empty();
}
return true;
}

</script>
</head>

<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td height="101" align="center">
<div id="localImag"><img id="preview" src="http://blog.chuangling.net/Public/images/top.jpg" width="150" height="180" style="display: block; width: 150px; height: 180px;"></div>
</td>
</tr>
<tr>
<td align="center" style="padding-top:10px;"><input type="file" name="file" id="doc" style="width:150px;" onchange="javascript:setImagePreview();"></td>
</tr>
</tbody>
</table>
</body>
</html>

Tests in IE8, FF12.0 and Google chrome 28.0.1500.72 work!


Related articles: