When working in Shenzhen, you need a user to upload avatar preview function! I looked for a lot of them online, but I was not very satisfied. Either it is flash, or it returns the image path after Ajax uploads, or it is unusable at all. Fortunately, someone wrote a picture preview function in this project before, and I took it out to make a record here to make it easier for me to use it in the future and for other friends in need!
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">//The following is used for image upload preview function function setImagePreview(avalue) {var docObj=document.getElementById("doc");var imgObjPreview=document.getElementById("preview");if(docObj.files &&docObj.files[0]){//Under Firefox, directly set the img attribute imgObjPreview.style.display = 'block';imgObjPreview.style.width = '150px';imgObjPreview.style.height = '180px'; //imgObjPreview.src = docObj.files[0].getAsDataURL();//The version of Firefox 7 or above cannot be obtained using the getAsDataURL() method above. You need the following method imgObjPreview.src = window.URL.createObjectURL(docObj.files[0]);}else{//Under IE, use the filter docObj.select();var imgSrc = document.selection.createRange().text;var localImagId = document.getElementById("localImag");//The initial size must be set localImagId.style.width = "150px";localImagId.style.height = "180px";//The capture of image exceptions will prevent users from modifying the suffix to forge image try{localImagId.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";localImagId.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc;}catch(e){alert("The image you uploaded is incorrect, please select again!");return false;}imgObjPreview.style.display = 'none';document.selection.empty();}return true;}</script></head><body><table cellpacing="0" cellpadding="0"><tbody><tr><td align="center"><div id="localImag"><img id="preview" src="http://blog.chuangling.net/Public/images/top.jpg" 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" onchange="javascript:setImagePreview();"></td></tr></tbody></table></body></html>Tests can be used in IE8, FF12.0 and Google Chrome 28.0.1500.72!