EXTJS+STRUTS图片上传

Posted 星期二, 03/10/2009 - 23:56 by andy_ghg

总所周知,Javascript代码是无法直接访问本地文件的,因此,做到真正的可预览还是比较麻烦的,这里我只是做了个表面上开起来像是可预览图片的一个小程序.

申明:EXTJS上传照片是会出现刷新的,但是在页面上感觉不出来已经被刷新过,因为其内部还是创建了一个iframe作为上传的临时页面的,它刷新的只是这个临时的iframe而已.

//==================第一步,copy官方Demo上的js代码(名字为 FielUploadField.js)=======================

 

Ext.form.FileUploadField = Ext.extend(Ext.form.TextField,  {

    

    buttonText: 'Browse...',

    

    buttonOnly: false,

    

    buttonOffset: 3,

    

 

    // private

    readOnly: true,

 

    

    autoSize: Ext.emptyFn,

 

    // private

    initComponent: function(){

        Ext.form.FileUploadField.superclass.initComponent.call(this);

 

        this.addEvents(

            

            'fileselected'

        );

    },

 

    // private

    onRender : function(ct, position){

        Ext.form.FileUploadField.superclass.onRender.call(this, ct, position);

 

        this.wrap = this.el.wrap({cls:'x-form-field-wrap x-form-file-wrap'});

        this.el.addClass('x-form-file-text');

        this.el.dom.removeAttribute('name');

 

        this.fileInput = this.wrap.createChild({

            id: this.getFileInputId(),

            name: this.name||this.getId(),

            cls: 'x-form-file',

            tag: 'input', 

            type: 'file',

            size: 1

        });

 

        var btnCfg = Ext.applyIf(this.buttonCfg || {}, {

            text: this.buttonText

        });

        this.button = new Ext.Button(Ext.apply(btnCfg, {

            renderTo: this.wrap,

            cls: 'x-form-file-btn' + (btnCfg.iconCls ? ' x-btn-icon' : '')

        }));

 

        if(this.buttonOnly){

            this.el.hide();

            this.wrap.setWidth(this.button.getEl().getWidth());

        }

 

        this.fileInput.on('change', function(){

            var v = this.fileInput.dom.value;

            this.setValue(v);

            this.fireEvent('fileselected', this, v);

        }, this);

    },

 

    // private

    getFileInputId: function(){

        return this.id+'-file';

    },

 

    // private

    onResize : function(w, h){

        Ext.form.FileUploadField.superclass.onResize.call(this, w, h);

 

        this.wrap.setWidth(w);

 

        if(!this.buttonOnly){

            var w = this.wrap.getWidth() - this.button.getEl().getWidth() - this.buttonOffset;

            this.el.setWidth(w);

        }

    },

 

    // private

    preFocus : Ext.emptyFn,

 

    // private

    getResizeEl : function(){

        return this.wrap;

    },

 

    // private

    getPositionEl : function(){

        return this.wrap;

    },

 

    // private

    alignErrorIcon : function(){

        this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]);

    }

 

});

Ext.reg('fileuploadfield', Ext.form.FileUploadField);

 

 

//===================第二步,继续copy官方Demo上的CSS样式表文件(是否必须我没测试,文件名随意)=======================

 

 

 

 

.x-form-file-wrap {

    position: relative;

    height: 22px;

}

.x-form-file-wrap .x-form-file {

position: absolute;

right: 0;

-moz-opacity: 0;

filter:alpha(opacity: 0);

opacity: 0;

z-index: 2;

    height: 22px;

}

.x-form-file-wrap .x-form-file-btn {

position: absolute;

right: 0;

z-index: 1;

}

.x-form-file-wrap .x-form-file-text {

    position: absolute;

    left: 0;

    z-index: 3;

    color: #777;

}

//====================第三步,编写我们自己的JS==========================

var photoName=null;//后面要用到这个

var formPanel=new Ext.FormPanel({

//非关键性代码略去

items:[{

html:"<img id="p" src="../empPhoto/default.png"; height="180";>"//先放一个默认图片

}]

})

 

//===================第四步,创建上传组件=============================

 

 

var upload = new Ext.form.FileUploadField({

id : 'form-file',

fieldLabel : '照片',

name : 'ff',//就是后台要获取的name

buttonCfg : {

text : '',

iconCls : 'pluginIcon'

},

listeners : {

//此事件请参考FileUploadField.js里面的代码

'fileselected' : function() {

var x = upload.getValue();

if (!x || !y)

return;

var patn = /\.jpg$|\.jpeg$|\.gif$|\.png&/i;//判断文件后缀名

if (!patn.test(x)) {

alert("您选择的不是图像文件!");

}

}

}

});

//创建一个FormPanel

var fp = new Ext.FormPanel({

fileUpload : true,

frame : true,

baseCls : 'x-plain',

layout : 'form',

labelWidth : 50,

defaults : {

anchor : '95%',

allowBlank : false

},

items : [upload]//把上面的对象加入到此FormPanel里

});

var addPhotoWin;//创建一个window用于显示上面的FormPanel,因为在IE和火狐中,是不允许出现嵌套form表单的(Google浏览器可以...汗一个)

var btn = Ext.get('addPhoto');

btn.on('click', function() {

if (!addPhotoWin) {

addPhotoWin = new Ext.Window({

frame : true,

layout : 'fit',

width : 300,

modal : true,

height : 130,

title : '上传照片',

defaults : {

style : "padding:10px;"

},

resizable : false,

closeAction : 'hide',

items : [fp],

buttons : [{

text : '保存',

id : 'save',

handler : function() {

if (fp.getForm().isValid()) {

//这里正常提交表单,就跟普通表单一样.

fp.getForm().submit({

url : 'basicEmployees.do?method=addPhoto',

method : 'POST',

waitMsg : '正在上传照片...',

success : function(fp, o) {

//接收后台返回的数据,暂时看不懂就先不用看,看完后台代码后就什么都知道了

photoName = o.result.data;//将后台返回上来的文件名赋值给它,以后就可以通过它来提交到数据库了.数据库中只要保存图片名称即可

var dom = document.getElementByIdx('p');//获得刚才Panel里面的html的id为p的dom对象

dom.src = "../empPhoto/" + photoName

+ "";//修改dom对象的属性,因为id为p的dom对象是个img,所以可以直接点他的src修改他图片路径

}

});

}

}

}, {

text : '重置',

handler : function() {

fp.getForm().reset();

}

}]

});

};

addPhotoWin.show();

});

 

//===================至此,前台搞定====================

//===================后台开始=======================/

//Struts的上传应该大家都很熟悉了,很简单的一个东西.就是先在form中加入一个FormFile(这玩意儿是个接口....)属性,并且提供get,set方法

//import org.apache.struts.upload.FormFile;

 

private FormFile ff;

 

 

 

public FormFile getFf() {

return ff;

}

 

public void setFf(FormFile ff) {

this.ff = ff;

}

 

//=======================Action中的代码(DispatchAction)====================

 

public ActionForward addPhoto(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response) throws IOException {

BasicEmployeesForm basicEmployeesForm=(BasicEmployeesForm)form;//

FormFile ff = basicEmployeesForm.getFf();//实例化FormFile

if (ff != null) {

System.out.println(ff.getFileName());

String name = ff.getFileName();//获得文件名

int index = name.lastIndexOf(".");

String type = name.substring(index, name.length());//获得文件后缀

String uuid = UUID.randomUUID().toString();//通过uuid生成一个唯一字符串,目的是保证此文件的唯一性

String savePath = request.getSession().getServletContext()

.getRealPath("/");//获得系统运行路径

System.out.println(savePath);

FileOutputStream fps = new FileOutputStream(savePath + "empPhoto\\"

+ uuid + type);//文件流路径,这里的文件名修改成了uuid+type,例如8s5d1-4785-8d5a2-7a8x52-7a41s.png

fps.write(ff.getFileData());//写入文件

fps.flush();//搽干净屁股

fps.close();//关闭文件流

response.getWriter().write(

"{success:true,data:'" + uuid + type + "'}");//返回已经上传到服务器的文件的文件名,在前台获取此文件名之后就可以根据此文件名修改那个默认头像<img>便签的src路径了

} else {

response.getWriter().write("{success:false}");

}

return null;

}

 

 

 

//=====================可能写的有点乱,不足之处大家多包含.....由于项目还在开发中...没法把半成品打包上载....不好意思,无法提供源码下载====================

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值