插件详解:
/** * 上传图片预览 **/ (function($){ $.fn.previewUpload=function(option){ var defaultOption={ fileInput:this, "150px", height:"200px", imgWrapId:{}, imgId:{}, } $(defaultOption.fileInput).change(function(){ var fileInputId=defaultOption.fileInput.attr("id"); $.extend(defaultOption,option); if(!defaultOption.imgWrapId||!defaultOption.imgId||$("#"+defaultOption.imgId).length==0){ alert("没有找到图片控件"); return ; } var files=defaultOption.fileInput[0].files; if (files && files[0]) { var reader = new FileReader(); reader.onload = function (e) { $('#'+defaultOption.imgId).attr('src', e.target.result).width(defaultOption.width).height(defaultOption.height); }; reader.readAsDataURL(files[0]); } else { //IE下,使用滤镜 var docObj = document.getElementById(fileInputId); docObj.select(); //解决IE9下document.selection拒绝访问的错误 docObj.blur(); var imgSrc = document.selection.createRange().text; var localImagId = document.getElementById(defaultOption.imgWrapId); $('#'+defaultOption.imgWrapId).width(defaultOption.width).height(defaultOption.height); //必须设置初始大小 //图片异常的捕捉,防止用户修改后缀来伪造图片 try { localImagId.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)"; localImagId.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc; } catch (e) { alert("您上传的图片格式不正确,请重新选择!"); return false; } $('#'+defaultOption.imgId).hide(); document.selection.empty(); } }); } })(jQuery);
Html中实现:
<body> <input type='file' id="doc" value="浏览" /> <div id="imgWrap"> <img id="img_prev" src="" alt="your image" /> </div> <script type="text/javascript> $(function(){ $("#doc").previewUpload({ "150px", height:"200px", imgWrapId:"imgWrap", imgId:"img_prev" }); }); </script> </body>