extjs上传文件fileUpload的方法

上传文件要是用asp.net的控件上传其实是很简单的问题,要是为了用户体验的提高很多的web开发人员都会采取很炫的ajax上传。

或是用flash想用的控件上传。今天我们看看extjs中如何很炫的上传文件或图片。

查了查资料发现extjs上传文件需要一个js文件FileUploadField.js,在extjs类库文件里可以找到。

FileUploadField.js代码如下:

/*!
 * Ext JS Library 3.2.0
 * Copyright(c) 2006-2010 Ext JS, Inc.
 * licensing@extjs.com
 * http://www.extjs.com/license
 */
Ext.ns('Ext.ux.form');

/**
 * @class Ext.ux.form.FileUploadField
 * @extends Ext.form.TextField
 * Creates a file upload field.
 * @xtype fileuploadfield
 */
Ext.ux.form.FileUploadField = Ext.extend(Ext.form.TextField,  {
    /**
     * @cfg {String} buttonText The button text to display on the upload button (defaults to
     * 'Browse...').  Note that if you supply a value for {@link #buttonCfg}, the buttonCfg.text
     * value will be used instead if available.
     */
    buttonText: 'Browse...',
    /**
     * @cfg {Boolean} buttonOnly True to display the file upload field as a button with no visible
     * text field (defaults to false).  If true, all inherited TextField members will still be available.
     */
    buttonOnly: false,
    /**
     * @cfg {Number} buttonOffset The number of pixels of space reserved between the button and the text field
     * (defaults to 3).  Note that this only applies if {@link #buttonOnly} = false.
     */
    buttonOffset: 3,
    /**
     * @cfg {Object} buttonCfg A standard {@link Ext.Button} config object.
     */

    // private
    readOnly: true,

    /**
     * @hide
     * @method autoSize
     */
    autoSize: Ext.emptyFn,

    // private
    initComponent: function(){
        Ext.ux.form.FileUploadField.superclass.initComponent.call(this);

        this.addEvents(
            /**
             * @event fileselected
             * Fires when the underlying file input field's value has changed from the user
             * selecting a new file from the system file selection dialog.
             * @param {Ext.ux.form.FileUploadField} this
             * @param {String} value The file value returned by the underlying file input field
             */
            'fileselected'
        );
    },

    // private
    onRender : function(ct, position){
        Ext.ux.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.createFileInput();

        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.bindListeners();
        this.resizeEl = this.positionEl = this.wrap;
    },
   
    bindListeners: function(){
        this.fileInput.on({
            scope: this,
            mouseenter: function() {
                this.button.addClass(['x-btn-over','x-btn-focus'])
            },
            mouseleave: function(){
                this.button.removeClass(['x-btn-over','x-btn-focus','x-btn-click'])
            },
            mousedown: function(){
                this.button.addClass('x-btn-click')
            },
            mouseup: function(){
                this.button.removeClass(['x-btn-over','x-btn-focus','x-btn-click'])
            },
            change: function(){
                var v = this.fileInput.dom.value;
                this.setValue(v);
                this.fireEvent('fileselected', this, v);   
            }
        });
    },
   
    createFileInput : function() {
        this.fileInput = this.wrap.createChild({
            id: this.getFileInputId(),
            name: this.name||this.getId(),
            cls: 'x-form-file',
            tag: 'input',
            type: 'file',
            size: 1
        });
    },
   
    reset : function(){
        this.fileInput.remove();
        this.createFileInput();
        this.bindListeners();
        Ext.ux.form.FileUploadField.superclass.reset.call(this);
    },

    // private
    getFileInputId: function(){
        return this.id + '-file';
    },

    // private
    onResize : function(w, h){
        Ext.ux.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
    onDestroy: function(){
        Ext.ux.form.FileUploadField.superclass.onDestroy.call(this);
        Ext.destroy(this.fileInput, this.button, this.wrap);
    },
   
    onDisable: function(){
        Ext.ux.form.FileUploadField.superclass.onDisable.call(this);
        this.doDisable(true);
    },
   
    onEnable: function(){
        Ext.ux.form.FileUploadField.superclass.onEnable.call(this);
        this.doDisable(false);

    },
   
    // private
    doDisable: function(disabled){
        this.fileInput.dom.disabled = disabled;
        this.button.setDisabled(disabled);
    },


    // private
    preFocus : Ext.emptyFn,

    // private
    alignErrorIcon : function(){
        this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]);
    }

});

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

// backwards compat
Ext.form.FileUploadField = Ext.ux.form.FileUploadField;

fileupload.html,显示上传的效果代码如下:

<!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>
    <title></title>
    <link rel="stylesheet" type="text/css" href="ext/resources/css/ext-all.css" mce_href="ext/resources/css/ext-all.css" />
 	<script. type="text/javascript" src="ext/adapter/ext/ext-base.js" mce_src="ext/adapter/ext/ext-base.js"></script>
    <script. src="ext/ext-all-debug.js" mce_src="ext/ext-all-debug.js" type="text/javascript"></script>
    <script. src="js/FileUploadField.js" mce_src="js/FileUploadField.js" type="text/javascript"></script>
    <style. type=text/css>        .upload-icon {
            background: url('images/image_add.png') no-repeat 0 0 !important;
        }
    .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;
    }
    </style>

    <script. type="text/javascript"><!--
        Ext.onReady(function() {

            Ext.QuickTips.init();

            var msg = function(title, msg) {
                Ext.Msg.show({
                    title: title,
                    msg: msg,
                    minWidth: 200,
                    modal: true,
                    icon: Ext.Msg.INFO,
                    buttons: Ext.Msg.OK
                });

            };
            
            var fp = new Ext.FormPanel({
                renderTo: 'fi-form',
                fileUpload: true,
                width: 500,
                frame. true,
                title: '图片上传操作',
                autoHeight: true,
                bodyStyle. 'padding: 10px 10px 0 10px;',
                labelWidth: 50,
                defaults: {
                    anchor: '95%',
                    allowBlank: false,
                    msgTarget: 'side'
                },
                items: [{
                    xtype: 'textfield',
                    fieldLabel: 'Name',
                    name:"txtname"
                }, {
                    xtype: 'fileuploadfield',
                    id: 'form-file',
                    emptyText: 'Select an image',
                    fieldLabel: 'Photo',
                    name: 'photo-path',
                    buttonText: '',
                    buttonCfg: {
                        iconCls: 'upload-icon'
                    }
}],
                    buttons: [{
                        text: 'Save',
                        handler: function() {
                            if (fp.getForm().isValid()) {
                                fp.getForm().submit({
                                    url: 'Default.aspx',//后台处理的页面
                                    waitMsg: 'Uploading your photo...',
                                    success: function(fp, o) {
                                        msg('Success', 'Processed file "' + o.result.files + '" on the server');
                                    }
                                });
                            }
                        }
                    }, {
                        text: 'Reset',
                        handler: function() {
                            fp.getForm().reset();
                        }
}]
                    });
                });
    
// --></script>
</head>
<body>
<div id="fi-form"></div>

</body>
</html>

以上的代码都是显示上传的内容,而上传的关键在于后台是如何操作。

可以新建一个Default.aspx页面来进行上传的处理。在上传的提交时都是post进行提交的,所以关键是在后台要获取上传的对象。

在Page_Load中加入代码:

string newname = Request["txtname"]; //获取重命名
HttpPostedFile postedFile = Request.Files["photo-path"];//获取上传信息对象
string filename = postedFile.FileName;//获取上传的文件路径
string tempPath = System.Configuration.ConfigurationManager.AppSettings["NewsFolderPath"];//获取保存文件夹路径,我是设置在webconfig中了。
string savepath = Server.MapPath(tempPath);//获取保存路径
        string sExtension = filename.Substring(filename.LastIndexOf('.'));//获取拓展名
        if (!Directory.Exists(savepath))
            Directory.CreateDirectory(savepath);
        string sNewFileName = DateTime.Now.ToString("yyyyMMddhhmmsfff");
        postedFile.SaveAs(savepath + @"/" + sNewFileName + sExtension);//保存

        Response.Write("{success:true, files:'文件路径:" + filename + " 重命名" + newname + "'}");

演示图如下:

 

上传中:

 

 

 

上传ok:

diosserew -
共有0个回答