Jquery Ajax文件上传插件Uploadify详解(下)


      在我的上一篇随笔里介绍了Jquery文件上传插件Uploadify的一些基本配置参数、事件和方法,都是一些死的东西,这篇随笔里就介绍一些服务器端的配置和Demo。

     用VS2010写Demo的时候,发现一个奇怪的现象,在FF、Chrome、IE6-8浏览器中文件上传一切正常,唯独在IE9中,Uploadify按钮点不动,无法打开选择文件对话框,郁闷啊,找原因:更新Flash Player、调整CSS样式,都不行……最后的解决办法竟然是在IIS中为demo单独配置一个站点,问题完美解决了!我也不知道Uploadify为什么在VS2010自带的调试服务器里面会出现这样的问题,而且只针对IE9……不管了,这不是重点,大家在测试uploadify时候注意一下这一点就可以了。

     下面就直接上例子吧……图片是源码文件结构和Html部分代码

 

  下面是服务器端代码:

UploadifyHandler.ashx.cs
 1         public void ProcessRequest(HttpContext context)
 2         {
 3             context.Response.ContentType = "text/plain";
 4             context.Response.Expires = -1;
 5             //Get the post uploading file object. Uploadify default parameter is "Filedata"
 6             HttpPostedFile file = context.Request.Files["Filedata"];
 7             //Get the physical upload files path. You can put it in the web.config
 8             string uploadPath = HttpContext.Current.Server.MapPath("~/UserFiles/Files") + "\\";
 9             if (file != null)
10             {
11                 try
12                 {
13                     //Create the uploadfile directory if is not existed
14                     if (!Directory.Exists(uploadPath)) Directory.CreateDirectory(uploadPath);
15                     //save file. you can execute some sql opeation here
16                     file.SaveAs(uploadPath + file.FileName);
17                     context.Response.Write("Upload Successed!");
18                 }
19                 catch (Exception ex)
20                 {
21                     context.Response.Write(string.Format("Error:System error {0}", ex.Message.ToString()));
22                 }
23             }
24             else
25             {
26                 context.Response.Write("Error:File object can't be null");
27             }
28         }

    这是一个最简单的例子,看一些资料说Uploadify对中文的支持不是很好,但是我自己测试了一下,3.2的版本好像没有这个问题。受之前版本的影响,一直想通过在后台返回某些值去触发onUploadError事件,结果不行,不论是返回0还是false或是其他值,前台这边Uploadify获得的状态都是Complate,触发的事件都是onUploadSuccess,找了几天的原因发现是自己的理解出了问题:只要前台将File传到服务器端,服务器端返回200响应,这个过程就被认为是Completed,除此之外的情况才会触发onUploadError事件,比如服务器端返回的状态码是500。所以想要人为的在前台显示自定义的错误信息还是要通过在onUploadSuccess函数中写脚本去判断返回值实现。Uploadify中OnUploadError事件是这么定义的:

onUploadError
 1         // Triggered when a file upload returns an error
 2         onUploadError : function(file, errorCode, errorMsg) {
 3             // Load the swfupload settings
 4             var settings = this.settings;
 5 
 6             // Set the error string
 7             var errorString = 'Error';
 8             switch(errorCode) {
 9                 case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
10                     errorString = 'HTTP Error (' + errorMsg + ')';
11                     break;
12                 case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL:
13                     errorString = 'Missing Upload URL';
14                     break;
15                 case SWFUpload.UPLOAD_ERROR.IO_ERROR:
16                     errorString = 'IO Error';
17                     break;
18                 case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
19                     errorString = 'Security Error';
20                     break;
21                 case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
22                     alert('The upload limit has been reached (' + errorMsg + ').');
23                     errorString = 'Exceeds Upload Limit';
24                     break;
25                 case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
26                     errorString = 'Failed';
27                     break;
28                 case SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND:
29                     break;
30                 case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
31                     errorString = 'Validation Error';
32                     break;
33                 case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
34                     errorString = 'Cancelled';
35                     this.queueData.queueSize   -= file.size;
36                     this.queueData.queueLength -= 1;
37                     if (file.status == SWFUpload.FILE_STATUS.IN_PROGRESS || $.inArray(file.id, this.queueData.uploadQueue) >= 0) {
38                         this.queueData.uploadSize -= file.size;
39                     }
40                     // Trigger the onCancel event
41                     if (settings.onCancel) settings.onCancel.call(this, file);
42                     delete this.queueData.files[file.id];
43                     break;
44                 case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
45                     errorString = 'Stopped';
46                     break;
47             }

 里面内置了这么10中错误,相应的ErrorCode如下:

SWFUpload.UPLOAD_ERROR={HTTP_ERROR:-200,MISSING_UPLOAD_URL:-210,IO_ERROR:-220,SECURITY_ERROR:-230,UPLOAD_LIMIT_EXCEEDED:-240,UPLOAD_FAILED:-250,
SPECIFIED_FILE_ID_NOT_FOUND:-260,FILE_VALIDATION_FAILED:-270,FILE_CANCELLED:-280,UPLOAD_STOPPED:-290};

 所以可以在onUploadError函数里面判断errorCode从而更改内置的错误信息显示。

    很多时候我们都需要限制用户上传文件的类型,一方面安全,另一方面也利于维护,所以在前台通过JS限制文件拓展名,后台验证文件MIME类型来实现,在这里的假设只能上传PDF、RAR、JPG格式的文件;除了限制文件类型,我们还需要限制文件的大小,不过ASP.NET默认的上传文件限制为4M,可以在Web.config里面system.web节点下新增httpRuntime配置即可,如下,我设置的是最大上载字节数为10M,请求超时为5分钟:

<httpRuntime maxRequestLength="10240" executionTimeout="300"/>

 //TODO

 

 

 

 

 

posted @ 2012-09-25 01:03  Hans Huang  Views(2627)  Comments(0Edit  收藏  举报