Ext文件上传(使用swfupload插件)

其实Ext.form.TextField就是Ext的上传组件的,只要将其配置参数inputType设置为"file"就行了。上传文件除了文件输入框,还有一个重要的设置,就是需要将form的enctype属性设置为"multipart/form-data"。这个也很简单,在定义FormPanel的时候加入BasicForm的配置参数fileUpload,并设置为true就行了。

在Ext中使用标准上传方式最大的缺点就是文件输入框的宽度很难控制,与界面不是太协调,而且在不同浏览器中的显示是不同的。在Ext官方论坛中有很多替代办法,笔者比较喜欢的是SWFUpload。

SWFUpload使用Flash作为上传组件,文件选择可以设置为单选,也可以设置多选,而且可以控制选择文件的类型。执行文件选择不依赖于标准文件输入框,可以使用按钮、链接等多种方式执行,从而可以根据需要设置界面。SWFUpload的提交不依赖Form,其模式类似于Ajax提交,可以很容易的实现对上传的控制和显示上传进度。

SWFUpload的官方地址是:http://www.swfupload.org/。

在SWFUpload中有两个主要对象:file和Stats。

file对象主要是保存文件的一些基本信息,其结构如下:

{

id : string,  // SWFUpload 的文件编号,作为开始上传、取消上传的句柄

index : number, // 文件在上传队列中的索引

name : string, // 文件名,不包含路径

size : number, // 文件大小,单位为字节

type : string, // 文件类型

creationdate : Date, // 文件创建日期

modificationdate : Date, // 文件最后编辑日期

filestatus : number, // 文件状态

}
 

 

Stats对象主要提供上传队列中的信息,其结构如下:

{

in_progress : number // 1表示正在上传文件,0表示则不是

files_queued : number // 上传队列中的文件数量

successful_uploads : number // 已成功上传的文件数量

upload_errors : number // 上传失败的文件数量

upload_cancelled : number // 取消上传的文件数量

queue_errors : number // 触发了fileQueueError事件的文件数量

}
 

 

表1列出了SWFUpload的主要配置参数。

表1 SWFUpload的主要配置参数
 
参数
 类型
 描述
 
upload_url
 字符串
 文件上传地址
 
flash_url
 字符串
 SWFUpload使用的flash文件的绝对地址或相对地址
 
file_size_limit
 字符串
 限制上传文件的大小

格式为:值+单位

允许的单位有B、KB、MB和GB。如果不设置单位,则默认单位为KB

如果设置为0则无限制
 
file_upload_limit

 
 数字
 允许上传的文件数量,该值表示的是在上传页面没有被销毁前允许上传的文件数量。默认值为0,表示没有限制
 
file_queue_limit
 数字
 在一次上传过程中允许上传的文件数量,默认值为0,表示无限制
 
file_types
 字符串
 限制上传文件的类型。使用分号分隔各类型

例如:"*.jpg;*.gif"表示只允许上传扩展名为JPG和GIF的文件
 
file_post_name
 字符串
 服务器端接收文件的变量名,本属性只在Flash 9版本有效
 
requeue_on_error
 布尔值
 设置为true则当文件上传错误时重新返回队列等待上传,设置为false则不再上传
 
post_params
 对象
 JSON格式的与文件一起上传的参数,Flash 8版本不支持
 
file_types_description
 字符串
 在文件选择对话框显示的文本描述
 
flash_color
 颜色值
 设置包含flash的HTML标签的背景颜色,默认值是"#FFFFFF"
 
debug
 布尔值
 设置为true则显示调试
 
file_queued_handler
 函数
 当选择文件对话框关闭时执行该函数,函数会传入一个file对象
 
upload_start_handler
 函数
 文件开始上传时执行该函数,函数会传入一个file对象
 
upload_progress_handler
 函数
 通过该函数显示上传进度,函数传入一个file对象与文件已上传的字节数
 
upload_success_handler
 函数
 单个文件上传成功时执行该函数,函数传入一个file对象与服务器端返回的信息
 
upload_error_handler
 函数
 单个文件上传失败或中断时执行该函数,函数传入一个file对象、错误代码与错误信息
 
file_queue_error_handler
 函数
 文件未能加入队列时执行该函数,函数传入一个file对象、错误代码与错误信息
 

 

表2列出了SWFUpload的主要方法。

表2SWFUpload的主要方法
 
方法
 描述
 
selectFile
 功能:打开选择文件对话框,但允许选择一个文件

语法:selectFile()

参数: 无

返回值:无

例子:swfu.selectFile()
 
selectFiles
 功能:打开选择文件对话框,允许选择多个文件

语法:selectFiles()

参数: 无

返回值:无

例子:swfu.selectFiles()
 
startUpload
 功能:开始上传文件

语法:startUpload ([file_id])

参数:

     file_id:可选值,要上传的文件编号,如果不设置则上传队列里的第一个文件

返回值:无

例子:swfu.startUpload ()
 
cancelUpload
 功能:取消上传某个文件

语法:cancelUpload ([file_id])

参数:

     file_id:可选值,要取消上传的文件编号,如果不设置则上传队列里的第一个文件取消上传

返回值:无

例子:swfu.cancelUpload ()
 
stopUpload
 功能:中止上传

语法:stopUpload ()

参数: 无

返回值:无

例子:swfu.stopUpload ()
 
getStats
 功能:返回当前上传状态

语法:getStats ()

参数: 无

返回值:stats对象

例子:vat stats=swfu.getStats ()
 
setPostParams
 功能:设置提交的附加参数

语法:setPostParams(param_object)

参数:

    param_object:一个JSON对象

返回值:无

例子:swfu. setPostParams({id:1,title:'标题'})

该例子附加了两个提交参数,一个为id,值为1,一个为title,值为标题
 

 

要使用SWFUpload,需要在页面加载swfupload.js文件并设置好参数,尤其要注意Flash文件的路径。具体使用方法请看下面例子:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<html debug='true'>

<head>

  <title>上传文件</title>

         <meta http-equiv="content-type" content="text/html; charset=utf-8">

         <link rel="stylesheet" type="text/css" href="../lib/ext/resources/css/ext-all.css" />

        <script type="text/javascript" src="../lib/ext/ext-base.js"></script>

  <script type="text/javascript" src="../lib/ext/ext-all.js"></script> 

  <script type="text/javascript" src="../lib/ext/radiogroup.js"></script>

  <script type="text/javascript" src="../lib/ext/locale/ext-lang-zh_CN.js"></script>

         <script type="text/javascript" src="swfupload.js"></script>

</head>

<body>

         <h1 style="margin:20px 0px 0px 20px;">第4章 上传文件</h1>

         <br />

         <div style="padding-left:20px;">

<p>

    <div id="form1"></div><br>

    <div >执行操作:</div>

    <textarea id='op' rows="10" style="width:800px;"></textarea>

</p>

<br />

</div>

<script>

         var app={};

 

         var swfu;

 

 

         Ext.onReady(function(){

 

                   Ext.QuickTips.init();

                   Ext.form.Field.prototype.msgTarget = 'under';

 

                   swfu=new SWFUpload({

                            upload_url : "upload.ashx",

                            flash_url : "swfupload_f9.swf" ,

                            file_size_limit : "10240",

                            file_types : "*.jpg;*.gif",

                            file_post_name : "Filedata",

                            requeue_on_error : false,

                            post_params : {},

                            file_types_description:'图片',

                           flash_color : "#FFFFFF",

                           file_queued_handler : function(file){

                                     var filetype=(file.type.substr(1)).toUpperCase();

                                     if(filetype=='JPG' | filetype=='GIF'){

                                               swfu.startUpload();

                                     }else{

                                               Ext.Msg.alert('错误','只能上传JPG或GIF格式文件')

                                     }

                           },

                           upload_start_handler:function(file){Ext.Msg.progress('上传文件','正在上传文件:'+file.name,'0%');return true;},

                           upload_progress_handler:function(file,bytesloaded){

                                     var percent = Math.ceil((bytesloaded / file.size) * 100);

                                     Ext.Msg.updateProgress(percent/100,percent+'%');

                           },

                           upload_success_handler:function(file, server_data){

                                    var msg=Ext.decode(server_data);

                                    if(msg){

                                             if(msg.success){

                                                        Ext.getCmp('imagePane').body.dom.innerHTML="<img width='100' src='upload/"+msg.file+"'>"

                                                        Ext.get('op').dom.value+="----------------------------\n"

                                                                 +"执行回调函数:success\n"

                                                                 +"返回值:"+server_data+'\n';

                                                        var stats=swfu.getStats();

                                                        if(stats.files_queued>0)

                                                                           swfu.startUpload();

                                                       Ext.Msg.hide();

                                             }else{

                                                        Ext.Msg.alert('错误',msg.msg);

                                             }

                                    }else{

                                               Ext.Msg.alert('错误','上传错误!')

                                    }

                           },

                           upload_error_handler:function(file,error_code,message){

                                    Ext.Msg.alert('错误','上传文件"'+file.name+'"发生错误。<br>错误代码:'+error_code+'<br>'+'错误信息:'+message);

                           },

                           file_queue_error_handler:function(file,error_code,message){

                                     switch (error_code) {

                                     case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:

                                               Ext.Msg.alert('错误',"文件不允许超过300k!<br> 文件名: " + file.name + "<br> 大小: " + file.size );

                                               break;

                                     case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:

                                               Ext.Msg.alert('错误',"不允许上传0字节文件!<br> 文件名: " + file.name + "<br> 大小: " + file.size );

                                               break;

                                     case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:

                                               Ext.Msg.alert('错误',"已超出上传文件数量!<br> 文件名: " + file.name + "<br> 大小: " + file.size );

                                               break;

                                     case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:

                                               Ext.Msg.alert('错误',"不允许上传该类文件!<br> 文件名: " + file.name + "<br> 大小: " + file.size );

                                               break;

                                     default:

                                               Ext.Msg.alert('错误',"发生未知错误,错误代码:"+error_code+"!<br> 文件名: " + file.name + "<br> 大小: " + file.size );

                                               break;

                                     }

                           }

                   });

                  

                  

                   var frm = new Ext.form.FormPanel({  

                            applyTo: "form1",

                            width: 400,

                            height:300,

                            frame: true,

                            labelWidth:80,

                            labelSeparator:":",

                            title:'上传文件',

                            fileUpload:true,

                            items:[

                                     {

                                               xtype:'textfield',

                                               name:'title',

                                               fieldLabel:'标题',

                                               anchor:'-30',

                                               allowBlank:false

                                     },

                                     {

                                               xtype:'textfield',

                                               name:'Filedata',

                                               fieldLabel:'文件',

                                               anchor:'-30',

                                               allowBlank:false,

                                               inputType:'file'

                                     },

                          {layout:'column',border:false,items:[

                                    {columnWidth:.4,border:false,items: [

                                                        {

                                                                 xtype:'button',

                                                                 text:'上传文件',

                                                                 handler:function(){

                                                                          swfu.setPostParams({title:frm.form.findField("title").getValue()});

                                                                           swfu.selectFile();

                                                                 }

                                                        }

                                               ]},

                                    {columnWidth:.1,border:false,items: [

                                                        {xtype:'panel',html:'&nbsp;',height:26,border:false}

                                               ]},

                                    {columnWidth:.4,layout: 'form',border:false,items: [

                                                        {

                                                                 xtype:'button',

                                                                 text:'上传多个文件',

                                                                 handler:function(){

                                                                          swfu.setPostParams({title:frm.form.findField("title").getValue()});

                                                                           swfu.selectFiles();

                                                                 }

                                                        }

                                               ]}

                                     ]},

                                     {

                                               xtype:'panel',

                                               id:'imagePane',

                                               bodyStyle:'padding:5px',

                                               html:'&nbsp;',

                                               height:120,

                                               width:120                                      

                                     }

                            ],

             buttons: [{

                 text: '保存',

                 scope:this,

                 handler:function(){

                    if(frm.form.isValid()){

                             frm.form.doAction('submit',{

                                                                    waitTitle:'上传文件',

                                                                   waitMsg:'正在上传文件……',

                                                                           url:'upload.ashx',

                                                                           method:'post',

                                                                           params:'',

                                                                           success:function(form,action){

                                                                                    Ext.getCmp('imagePane').body.dom.innerHTML="<img width='100' src='upload/"+action.result.file+"'>"

                                                                                    Ext.get('op').dom.value+="----------------------------\n"

                                                                                             +"执行回调函数:success\n"

                                                                                             +"返回值:"+Ext.encode(action.result)+'\n';

                                                                           },

                                                                           failure:function(form,action){

                                                                                    Ext.get('op').dom.value+="----------------------------\n"

                                                                                             +"执行回调函数:failure\n"

                                                                                             +"返回值:"+Ext.encode(action.result)+'\n';

                                                                           }                                                                        

                             });

                    }

                 }           

             },{

                 text: '取消',

                 scope:this,

                 handler:function(){frm.form.reset();}

             }],

                   listeners:{

                            render:function(fp){

                                     fp.form.waitMsgTarget = fp.getEl();

                            }

                   }

                   });

 

                  

         })

</script>

</body>

</html>
 

 

例子中使用了两种方式实现文件上传,一种是标准方式,使用Form提交,一种使用SWFUpload。

标准方式的定义比较简单,在FormPanel定义中加入fileUpload参数并设置为true,然后将一个TextField的inputType设置为file就行了。保存的提交方式与一般的Form提交没什么区别。

SWFUpload的定义稍微复杂一点。首先在onReady函数外定义了一个swfu的全局变量,主要目的是使swfu成为一个全局的SWFUpload实例,以便在内部函数中能使用该实例。

本例子使用的Flash 9版本,而且swf文件与页面文件在同一目录,所以设置flash_url为swfupload_f9.swf。允许上传的文件大小限制为10兆,只能上传JPG和GIF文件,服务器端接收文件的参数名称为Filedata。

在file_queued_handler函数中先判别上传文件的扩展名是否符合要求,如果符合则执行startUpload方法开始上传文件。

upload_start_handler函数在文件开始时显示一个Ext进度条。

upload_progress_handler函数则根据已上传字节数计算上传进度并更新进度条。

upload_success_handler函数根据服务器端返回信息更新页面显示,并判断上传队列中是否还有文件未上传,如果有则继续上传。

upload_error_handler函数与file_queue_error_handler函数则在发生错误时显示错误信息。

在FormPanel中有两个按钮,一个用来演示上传单文件,一个用来演示上传多文件。单击后先根据标题输入框的值,设置一个附加提交参数title,然后执行selectFile方法或selectFiles方法打开文件选择对话框。对话框关闭后执行file_queued_handler函数开始上传文件。

文件上传后会在id为"'imagePane'"的Panel显示上传图片的缩略图。执行操作中也会显示返回的结果。

下面看看服务器端代码如下:

<%@ WebHandler Language="C#" Class="upload" %>

 

using System;

using System.Web;

using System.Collections;

using System.IO;

using System.Data.Common;

using System.Data;

 

 

public class upload : IHttpHandler {

   

    public void ProcessRequest (HttpContext context) {

      string outputStr = "{success:false,data:''}";

      HttpPostedFile jpeg_image_upload = context.Request.Files["Filedata"];

      string title= context.Request.Form["title"];

      string original_fielname = jpeg_image_upload.FileName.ToLower();

      string extname=original_fielname.Substring(original_fielname.LastIndexOf(".")+1,3);

      if (extname == "gif" | extname == "jpg")

      {

        try

        {

                 string path = context.Server.MapPath("./upload");

          DateTime dt = DateTime.Now;

          string newFilename = dt.ToString("yyyyMMddHHmmssfff")+"."+extname;

          jpeg_image_upload.SaveAs(path+"\\"+newFilename);

          outputStr = string.Format("{{success:true,data:'文件"{0}"上传成功,文件名:{1}',file:'{1}'}}",title,newFilename);

        }

        catch(Exception e)

        {

          outputStr = string.Format("{{success:false,data:'{0}'}}",e.Message);

        }

      }

      else

      {

        outputStr = "{success:false,data:'错误的文件类型!'}";

      }

      context.Response.Write(outputStr);

     

    }

 

你可能感兴趣的:(JavaScript,css,ext,Flash,FP)