Extjs 文件上传的实现方法

来源:互联网 发布:淘宝古装衣服图片 编辑:程序博客网 时间:2024/04/29 15:37

上传文件要是用asp.net的控件上传其实是很简单的问题,要是为了用户体验的提高很多的web开发人员都会采取很炫的ajax上传。一般情况都使用flash的控件上传。本文介绍使用EXTJS 实现文件的上传。

Extjs 要实现上传,需要一个js文件FileUploadField.js,在extjs类库文件里可以找到。当然也可以使用Ext.ux.UploadDialog.Dialog这个插件来实现上传。

FileUploadField.js代码:

 
  1. /*!
  2.  * Ext JS Library 3.2.0
  3.  * Copyright(c) 2006-2010 Ext JS, Inc.
  4.  * licensing@extjs.com
  5.  * http://www.extjs.com/license
  6.  */
  7. Ext.ns('Ext.ux.form');
  8. /**
  9.  * @class Ext.ux.form.FileUploadField
  10.  * @extends Ext.form.TextField
  11.  * Creates a file upload field.
  12.  * @xtype fileuploadfield
  13.  */
  14. Ext.ux.form.FileUploadField = Ext.extend(Ext.form.TextField,  {
  15.     /**
  16.      * @cfg {String} buttonText The button text to display on the upload button (defaults to
  17.      * 'Browse...').  Note that if you supply a value for {@link #buttonCfg}, the buttonCfg.text
  18.      * value will be used instead if available.
  19.      */
  20.     buttonText: 'Browse...',
  21.     /**
  22.      * @cfg {Boolean} buttonOnly True to display the file upload field as a button with no visible
  23.      * text field (defaults to false).  If true, all inherited TextField members will still be available.
  24.      */
  25.     buttonOnly: false,
  26.     /**
  27.      * @cfg {Number} buttonOffset The number of pixels of space reserved between the button and the text field
  28.      * (defaults to 3).  Note that this only applies if {@link #buttonOnly} = false.
  29.      */
  30.     buttonOffset: 3,
  31.     /**
  32.      * @cfg {Object} buttonCfg A standard {@link Ext.Button} config object.
  33.      */
  34.     // private
  35.     readOnly: true,
  36.     /**
  37.      * @hide
  38.      * @method autoSize
  39.      */
  40.     autoSize: Ext.emptyFn,
  41.     // private
  42.     initComponent: function(){
  43.         Ext.ux.form.FileUploadField.superclass.initComponent.call(this);
  44.         this.addEvents(
  45.             /**
  46.              * @event fileselected
  47.              * Fires when the underlying file input field's value has changed from the user
  48.              * selecting a new file from the system file selection dialog.
  49.              * @param {Ext.ux.form.FileUploadField} this
  50.              * @param {String} value The file value returned by the underlying file input field
  51.              */
  52.             'fileselected'
  53.         );
  54.     },
  55.     // private
  56.     onRender : function(ct, position){
  57.         Ext.ux.form.FileUploadField.superclass.onRender.call(this, ct, position);
  58.         this.wrap = this.el.wrap({cls:'x-form-field-wrap x-form-file-wrap'});
  59.         this.el.addClass('x-form-file-text');
  60.         this.el.dom.removeAttribute('name');
  61.         this.createFileInput();
  62.         var btnCfg = Ext.applyIf(this.buttonCfg || {}, {
  63.             text: this.buttonText
  64.         });
  65.         this.button = new Ext.Button(Ext.apply(btnCfg, {
  66.             renderTo: this.wrap,
  67.             cls: 'x-form-file-btn' + (btnCfg.iconCls ? ' x-btn-icon' : '')
  68.         }));
  69.         if(this.buttonOnly){
  70.             this.el.hide();
  71.             this.wrap.setWidth(this.button.getEl().getWidth());
  72.         }
  73.         this.bindListeners();
  74.         this.resizeEl = this.positionEl = this.wrap;
  75.     },
  76.     
  77.     bindListeners: function(){
  78.         this.fileInput.on({
  79.             scope: this,
  80.             mouseenter: function() {
  81.                 this.button.addClass(['x-btn-over','x-btn-focus'])
  82.             },
  83.             mouseleave: function(){
  84.                 this.button.removeClass(['x-btn-over','x-btn-focus','x-btn-click'])
  85.             },
  86.             mousedown: function(){
  87.                 this.button.addClass('x-btn-click')
  88.             },
  89.             mouseup: function(){
  90.                 this.button.removeClass(['x-btn-over','x-btn-focus','x-btn-click'])
  91.             },
  92.             change: function(){
  93.                 var v = this.fileInput.dom.value;
  94.                 this.setValue(v);
  95.                 this.fireEvent('fileselected'this, v);    
  96.             }
  97.         }); 
  98.     },
  99.     
  100.     createFileInput : function() {
  101.         this.fileInput = this.wrap.createChild({
  102.             id: this.getFileInputId(),
  103.             name: this.name||this.getId(),
  104.             cls: 'x-form-file',
  105.             tag: 'input',
  106.             type: 'file',
  107.             size: 1
  108.         });
  109.     },
  110.     
  111.     reset : function(){
  112.         this.fileInput.remove();
  113.         this.createFileInput();
  114.         this.bindListeners();
  115.         Ext.ux.form.FileUploadField.superclass.reset.call(this);
  116.     },
  117.     // private
  118.     getFileInputId: function(){
  119.         return this.id + '-file';
  120.     },
  121.     // private
  122.     onResize : function(w, h){
  123.         Ext.ux.form.FileUploadField.superclass.onResize.call(this, w, h);
  124.         this.wrap.setWidth(w);
  125.         if(!this.buttonOnly){
  126.             var w = this.wrap.getWidth() - this.button.getEl().getWidth() - this.buttonOffset;
  127.             this.el.setWidth(w);
  128.         }
  129.     },
  130.     // private
  131.     onDestroy: function(){
  132.         Ext.ux.form.FileUploadField.superclass.onDestroy.call(this);
  133.         Ext.destroy(this.fileInput, this.button, this.wrap);
  134.     },
  135.     
  136.     onDisable: function(){
  137.         Ext.ux.form.FileUploadField.superclass.onDisable.call(this);
  138.         this.doDisable(true);
  139.     },
  140.     
  141.     onEnable: function(){
  142.         Ext.ux.form.FileUploadField.superclass.onEnable.call(this);
  143.         this.doDisable(false);
  144.     },
  145.     
  146.     // private
  147.     doDisable: function(disabled){
  148.         this.fileInput.dom.disabled = disabled;
  149.         this.button.setDisabled(disabled);
  150.     },
  151.     // private
  152.     preFocus : Ext.emptyFn,
  153.     // private
  154.     alignErrorIcon : function(){
  155.         this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]);
  156.     }
  157. });
  158. Ext.reg('fileuploadfield', Ext.ux.form.FileUploadField);
  159. // backwards compat
  160. Ext.form.FileUploadField = Ext.ux.form.FileUploadField;

HTML代码:

 
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4.     <title></title>
  5.     <link rel="stylesheet" type="text/css" href="ext/resources/css/ext-all.css" mce_href="ext/resources/css/ext-all.css" />
  6.     <script type="text/javascript" src="ext/adapter/ext/ext-base.js" mce_src="ext/adapter/ext/ext-base.js"></script>
  7.     <script src="ext/ext-all-debug.js" mce_src="ext/ext-all-debug.js" type="text/javascript"></script>
  8.     <script src="js/FileUploadField.js" mce_src="js/FileUploadField.js" type="text/javascript"></script>
  9.     <style type=text/css>        .upload-icon {
  10.             background: url('images/image_add.png') no-repeat 0 0 !important;
  11.         }
  12.     .x-form-file-wrap {
  13.         position: relative;
  14.         height: 22px;
  15.     }
  16.     .x-form-file-wrap .x-form-file {
  17.         position: absolute;
  18.         right: 0;
  19.         -moz-opacity: 0;
  20.         filter:alpha(opacity: 0);
  21.         opacity: 0;
  22.         z-index: 2;
  23.         height: 22px;
  24.     }
  25.     .x-form-file-wrap .x-form-file-btn {
  26.         position: absolute;
  27.         right: 0;
  28.         z-index: 1;
  29.     }
  30.     .x-form-file-wrap .x-form-file-text {
  31.         position: absolute;
  32.         left: 0;
  33.         z-index: 3;
  34.         color: #777;
  35.     }
  36.     </style>
  37.     <script type="text/javascript"><!--
  38.         Ext.onReady(function() {
  39.             Ext.QuickTips.init();
  40.             var msg = function(title, msg) {
  41.                 Ext.Msg.show({
  42.                     title: title,
  43.                     msg: msg,
  44.                     minWidth: 200,
  45.                     modal: true,
  46.                     icon: Ext.Msg.INFO,
  47.                     buttons: Ext.Msg.OK
  48.                 });
  49.             };
  50.             
  51.             var fp = new Ext.FormPanel({
  52.                 renderTo: 'fi-form',
  53.                 fileUpload: true,
  54.                 width: 500,
  55.                 frame: true,
  56.                 title: '图片上传操作',
  57.                 autoHeight: true,
  58.                 bodyStyle: 'padding: 10px 10px 0 10px;',
  59.                 labelWidth: 50,
  60.                 defaults: {
  61.                     anchor: '95%',
  62.                     allowBlank: false,
  63.                     msgTarget: 'side'
  64.                 },
  65.                 items: [{
  66.                     xtype: 'textfield',
  67.                     fieldLabel: 'Name',
  68.                     name:"txtname"
  69.                 }, {
  70.                     xtype: 'fileuploadfield',
  71.                     id: 'form-file',
  72.                     emptyText: 'Select an image',
  73.                     fieldLabel: 'Photo',
  74.                     name: 'photo-path',
  75.                     buttonText: '',
  76.                     buttonCfg: {
  77.                         iconCls: 'upload-icon'
  78.                     }
  79. }],
  80.                     buttons: [{
  81.                         text: 'Save',
  82.                         handler: function() {
  83.                             if (fp.getForm().isValid()) {
  84.                                 fp.getForm().submit({
  85.                                     url: 'Default.aspx',//后台处理的页面
  86.                                     waitMsg: 'Uploading your photo...',
  87.                                     success: function(fp, o) {
  88.                                         msg('Success', 'Processed file "' + o.result.files + '" on the server');
  89.                                     }
  90.                                 });
  91.                             }
  92.                         }
  93.                     }, {
  94.                         text: 'Reset',
  95.                         handler: function() {
  96.                             fp.getForm().reset();
  97.                         }
  98. }]
  99.                     });
  100.                 });
  101.     
  102. // --></script>
  103. </head>
  104. <body>
  105. <div id="fi-form"></div>
  106. </body>
  107. </html>

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

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

在Page_Load中加入代码:

 
  1. string newname = Request["txtname"]; //获取重命名
  2. HttpPostedFile postedFile = Request.Files["photo-path"];//获取上传信息对象
  3. string filename = postedFile.FileName;//获取上传的文件路径
  4. string tempPath = System.Configuration.ConfigurationManager.AppSettings["NewsFolderPath"];//获取保存文件夹路径,我是设置在webconfig中了。
  5. string savepath = Server.MapPath(tempPath);//获取保存路径
  6.         string sExtension = filename.Substring(filename.LastIndexOf('.'));//获取拓展名
  7.         if (!Directory.Exists(savepath))
  8.             Directory.CreateDirectory(savepath);
  9.         string sNewFileName = DateTime.Now.ToString("yyyyMMddhhmmsfff");
  10.         postedFile.SaveAs(savepath + @"\" + sNewFileName + sExtension);//保存
  11.         Response.Write("{success:true, files:'文件路径:" + filename + " 重命名" + newname + "'}");

效果图如下:


上传完成:


原创粉丝点击