一般在上传图片时都会需要提前预览图片的上传效果,下面简单利用extjs插件来实现这个方法及解决在使用extjs上传时无法预览的问题。
在进行图片上传时,通常需要进行预览。而这种预览的行为通常是预览客户端的本地资源。下面就讲一下在Ext中是如何实现图片上传预览的。
1、首先,创建为预览图片创建一个控件,代码如下:
xtype : 'box', id : 'logoPic', width : 150, height : 200, autoEl : { tag : 'img', src : currentLogoPath, style : 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale);' }
2、然后再创建一个图片上传的控件,代码如下:
xtype : 'textfield', id : 'logoFile', name : 'logoFile', inputType : 'file', fieldLabel : '文件', width : 280, listeners : { 'render':function(){ var logoFileCmp = Ext.get('logoFile'); logoFileCmp.on('change',function(field,newValue,oldValue){ var picPath = logoFileCmp.getValue(); var url = 'file:///' + picPath; if(Ext.isIE){ var image = Ext.get('logoPic').dom; image.src = Ext.BLANK_IMAGE_URL; image.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = url; }else{ //支持FF Ext.get('logoPic').dom.src =Ext.get('logoFile').dom.files.item(0).getAsDataURL(); } },this); } }
3、为文件上传控件添加一个change事件。注意,在这里一定要用Ext.get方法取得控件,否则change事件会无效的。当有图片上传时,控件的值会发生改变,然后修改预览控件的src的值,以实现图片预览。Extjs解决上传图片预览,代码如下
{ width: 450, fileUpload: true, fieldLabel: '选择图片', items: [{ xtype: 'textfield', id: 'up_forth', name: 'up_forth', inputType: 'file', width: 300 }] } 预览box { columnWidth: .18, bodyStyle: ' margin:4px 10px 10px 5px', layout: 'form', items: [{ xtype: 'box', autoEl: { width: 150, height: 150, tag: 'div', id: 'browser_up_forth' } }] }
4、myfrom表示上传控件外围的FormPanel,, contril_id表示上传控件的ID,只要在程序上预览注册该方法就可以,preview (myfrom,'up_forth' ),代码如下
var preview = function (myform, control_id) { var img_reg = /.([jJ][pP][gG]){1}$|.([jJ][pP][eE][gG]){1}$|.([gG][iI][fF]){1}$|.([pP][nN][gG]){1}$|.([bB][mM][pP]){1}$/ myform.on('render', function (f) { myform.form.findField(control_id).on('render', function () { Ext.get(control_id).on('change', function (field, newValue, oldValue) { var obj = Ext.get(control_id).dom; var url = getFullPath(obj); if (img_reg.test(url)) { var newPreview = Ext.get('browser_' + control_id).dom; var showPic = Ext.get("showPic_" + control_id); if (showPic != null) { showPic.remove();//删除原来的图片 } var imgDiv = document.createElement("div"); imgDiv.id = "showPic_" + control_id; document.body.appendChild(imgDiv); imgDiv.style.width = "150px"; imgDiv.style.height = "150px"; imgDiv.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod = scale)"; imgDiv.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = url; newPreview.appendChild(imgDiv); } }, this); }, this); }, this); }
5、得到图片地址,代码如下
function getFullPath(obj) { if (obj) { // ie if (window.navigator.userAgent.indexOf("MSIE") >= 1) { obj.select(); return document.selection.createRange().text; } // firefox else if (window.navigator.userAgent.indexOf("Firefox") >= 1) { if (obj.files) { return obj.files.item(0).getAsDataURL(); } return obj.value; } return obj.value; } }
这样就能够解决extjs上传图片无法正常预览的问题。