《Ext详解与实践》节选:文件上传

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="ProgId" content="Word.Document"> <meta name="Generator" content="Microsoft Word 11"> <meta name="Originator" content="Microsoft Word 11"> <link rel="File-List" href="file:///C:%5CDOCUME%7E1%5CADMINI%7E1%5CLOCALS%7E1%5CTemp%5Cmsohtml1%5C01%5Cclip_filelist.xml"> <link rel="Edit-Time-Data" href="file:///C:%5CDOCUME%7E1%5CADMINI%7E1%5CLOCALS%7E1%5CTemp%5Cmsohtml1%5C01%5Cclip_editdata.mso"> <!--[if !mso]> <style> v/:* {behavior:url(#default#VML);} o/:* {behavior:url(#default#VML);} w/:* {behavior:url(#default#VML);} .shape {behavior:url(#default#VML);} </style> <![endif]--><smarttagtype namespaceuri="urn:schemas-microsoft-com:office:smarttags" name="chmetcnv" downloadurl=""></smarttagtype><!--[if gte mso 9]><xml> <w:WordDocument> <w:View>Normal</w:View> <w:Zoom>0</w:Zoom> <w:PunctuationKerning/> <w:DrawingGridVerticalSpacing>7.8 磅</w:DrawingGridVerticalSpacing> <w:DisplayHorizontalDrawingGridEvery>0</w:DisplayHorizontalDrawingGridEvery> <w:DisplayVerticalDrawingGridEvery>2</w:DisplayVerticalDrawingGridEvery> <w:ValidateAgainstSchemas/> <w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid> <w:IgnoreMixedContent>false</w:IgnoreMixedContent> <w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText> <w:Compatibility> <w:SpaceForUL/> <w:BalanceSingleByteDoubleByteWidth/> <w:DoNotLeaveBackslashAlone/> <w:ULTrailSpace/> <w:DoNotExpandShiftReturn/> <w:AdjustLineHeightInTable/> <w:BreakWrappedTables/> <w:SnapToGridInCell/> <w:WrapTextWithPunct/> <w:UseAsianBreakRules/> <w:DontGrowAutofit/> <w:UseFELayout/> </w:Compatibility> <w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel> </w:WordDocument> </xml><![endif]--><!--[if gte mso 9]><xml> <w:LatentStyles DefLockedState="false" LatentStyleCount="156"> </w:LatentStyles> </xml><![endif]--><!--[if !mso]><object classid="clsid:38481807-CA0E-42D2-BF39-B33AF135CC4D" id=ieooui></object> <style> st1/:*{behavior:url(#ieooui) } </style> <![endif]--><style> <!-- /* Font Definitions */ @font-face {font-family:宋体; panose-1:2 1 6 0 3 1 1 1 1 1; mso-font-alt:SimSun; mso-font-charset:134; mso-generic-font-family:auto; mso-font-pitch:variable; mso-font-signature:3 135135232 16 0 262145 0;} @font-face {font-family:黑体; panose-1:2 1 6 0 3 1 1 1 1 1; mso-font-alt:SimHei; mso-font-charset:134; mso-generic-font-family:auto; mso-font-pitch:variable; mso-font-signature:1 135135232 16 0 262144 0;} @font-face {font-family:"/@宋体"; panose-1:2 1 6 0 3 1 1 1 1 1; mso-font-charset:134; mso-generic-font-family:auto; mso-font-pitch:variable; mso-font-signature:3 135135232 16 0 262145 0;} @font-face {font-family:"/@黑体"; panose-1:2 1 6 0 3 1 1 1 1 1; mso-font-charset:134; mso-generic-font-family:auto; mso-font-pitch:variable; mso-font-signature:1 135135232 16 0 262144 0;} /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal {mso-style-parent:""; margin:0cm; margin-bottom:.0001pt; text-align:justify; text-justify:inter-ideograph; line-height:150%; mso-pagination:none; font-size:10.0pt; mso-bidi-font-size:12.0pt; font-family:"Times New Roman"; mso-fareast-font-family:宋体; mso-font-kerning:1.0pt;} a:link, span.MsoHyperlink {color:blue; text-decoration:underline; text-underline:single;} a:visited, span.MsoHyperlinkFollowed {color:purple; text-decoration:underline; text-underline:single;} p.2, li.2, div.2 {mso-style-name:"样式 首行缩进/: 2 字符"; margin:0cm; margin-bottom:.0001pt; text-align:justify; text-justify:inter-ideograph; text-indent:20.0pt; mso-char-indent-count:2.0; line-height:150%; mso-pagination:none; font-size:10.0pt; font-family:"Times New Roman"; mso-fareast-font-family:宋体; mso-bidi-font-family:宋体; mso-font-kerning:1.0pt;} /* Page Definitions */ @page {mso-page-border-surround-header:no; mso-page-border-surround-footer:no;} @page Section1 {size:612.0pt 792.0pt; margin:72.0pt 90.0pt 72.0pt 90.0pt; mso-header-margin:36.0pt; mso-footer-margin:36.0pt; mso-paper-source:0;} div.Section1 {page:Section1;} --> </style> <!--[if gte mso 10]> <style> /* Style Definitions */ table.MsoNormalTable {mso-style-name:普通表格; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-parent:""; mso-padding-alt:0cm 5.4pt 0cm 5.4pt; mso-para-margin:0cm; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:10.0pt; font-family:"Times New Roman"; mso-fareast-font-family:"Times New Roman"; mso-ansi-language:#0400; mso-fareast-language:#0400; mso-bidi-language:#0400;} table.MsoTableGrid {mso-style-name:网格型; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; border:solid windowtext 1.0pt; mso-border-alt:solid windowtext .5pt; mso-padding-alt:0cm 5.4pt 0cm 5.4pt; mso-border-insideh:.5pt solid windowtext; mso-border-insidev:.5pt solid windowtext; mso-para-margin:0cm; mso-para-margin-bottom:.0001pt; text-align:justify; text-justify:inter-ideograph; line-height:150%; mso-pagination:none; font-size:10.0pt; font-family:"Times New Roman"; mso-ansi-language:#0400; mso-fareast-language:#0400; mso-bidi-language:#0400;} </style> <![endif]-->

Ext没提供上传组件?很多人都会有这疑问。

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

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

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

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

SWFUpload中有两个主要对象:fileStats

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

字符串

限制上传文件的大小

格式为:值+单位

允许的单位有BKBMBGB。如果不设置单位,则默认单位为KB

如果设置为0则无限制

file_upload_limit

数字

允许上传的文件数量,该值表示的是在上传页面没有被销毁前允许上传的文件数量。默认值为0,表示没有限制

file_queue_limit

数字

在一次上传过程中允许上传的文件数量,默认值为0,表示无限制

file_types

字符串

限制上传文件的类型。使用分号分隔各类型

例如:“*.jpg;*.gif”表示只允许上传扩展名为JPGGIF的文件

file_post_name

字符串

服务器端接收文件的变量名,本属性只在Flash 9版本有效

requeue_on_error

布尔值

设置为true则当文件上传错误时重新返回队列等待上传,设置为false则不再上传

post_params

对象

JSON格式的与文件一起上传的参数,Flash 8版本不支持

file_types_description

字符串

在文件选择对话框显示的文本描述

flash_color

颜色值

设置包含flashHTML标签的背景颜色,默认值是“#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 "-//W<chmetcnv tcsc="0" numbertype="1" negative="False" hasspace="False" sourcevalue="3" unitname="C" w:st="on">3C</chmetcnv>//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('错误','只能上传JPGGIF格式文件')

}

},

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,然后将一个TextFieldinputType设置为file就行了。保存的提交方式与一般的Form提交没什么区别。

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

本例子使用的Flash 9版本,而且swf文件与页面文件在同一目录,所以设置flash_urlswfupload_f9.swf。允许上传的文件大小限制为10兆,只能上传JPGGIF文件,服务器端接收文件的参数名称为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);

}

public bool IsReusable {

get {

return false;

}

}

}

一个很简单的只接收单文件的服务器端代码。代码中使用了客户端设置的参数Filedata接受文件数据:

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

代码中对文件扩展名进行了判断,如果是GIFJPG则保存文件,否则返回错误。服务器端返回格式使用了Ext的返回格式。

1是例子的运行结果。

《Ext详解与实践》节选:文件上传

先测试标准方式上传,在标题输入测试,然后单击“选择”按钮选择一幅图片,单击保存按钮。

2是文件上传后的显示。

《Ext详解与实践》节选:文件上传

根据返回值,参数title和文件都已成功上传。

继续单击“上传文件”按钮选择一幅图片。当选择文件窗口关闭,会出现一个进度条,可能会是一闪而过,看看返回值:

----------------------------

执行回调函数:success

返回值:{success:true,data:'文件“测试”上传成功,文件名:20080730174659265.jpg',file:'20080730174659265.jpg'}

参数titile与文件也同样正确上传。

可以继续单击“上传多个文件”测试上传多个文件的情况,这里就不再赘述了。

SWFUpload和标准模式不同,上传多个文件时是一个一个的文件上传的,而不是标准模式使用不同的参数同时上传。

SWFUpload最大的缺点是受浏览器Flash插件版本的限制,低于版本8Flash插件不起作用。如果使用版本9swf文件,则需要Flash插件版本为9以上才能用。