ajaxfileupload 上传插件

弄了几天的上传,总是各种不兼容,现在基本算是完善了。目前的状况是发布在我自己的笔记本上,用同事的电脑访问IE10、firefox、chrome都可以正常上传,还有其他不完善的地方,欢迎大家赐教。。。。

ajaxfileupload.js

  1 jQuery.extend({
  2     handleError: function (s, xhr, status, e) {
  3         // If a local callback was specified, fire it
  4         if (s.error) {
  5             s.error.call(s.context || s, xhr, status, e);
  6         }
  7
  8         // Fire the global callback
  9         if (s.global) {
 10             (s.context ? jQuery(s.context) : jQuery.event).trigger("ajaxError", [xhr, s, e]);
 11         }
 12     },
 13     createUploadIframe: function (id, uri) {
 14         //create frame
 15         var frameId = ‘jUploadFrame‘ + id;
 16         var io;
 17         var io = ‘<iframe id="‘ + frameId + ‘" name="‘ + frameId + ‘" style="position:absolute; top:-9999px; left:-9999px"‘;
 18         if (window.ActiveXObject) {
 19             if (typeof uri == ‘boolean‘) {
 20                 io += ‘ src="‘ + ‘javascript:false‘ + ‘"‘;
 21             }
 22             else if (typeof uri == ‘string‘) {
 23                 io += ‘ src="‘ + uri + ‘"‘;
 24             }
 25         }
 26         io += ‘ />‘;
 27         $(document.body).append($(io));
 28
 29         return jQuery("#" + frameId).get(0);
 30     },
 31     createUploadForm: function (id, fileElementId, data) {
 32         //create form
 33         var formId = ‘jUploadForm‘ + id;
 34         var fileId = ‘jUploadFile‘ + id;
 35         var form = jQuery(‘<form  action="" method="POST" name="‘ + formId + ‘" id="‘ + formId + ‘" enctype="multipart/form-data"></form>‘);
 36         if (data) {
 37             for (var i in data) {
 38                 jQuery(‘<input type="hidden" name="‘ + i + ‘" value="‘ + data[i] + ‘" />‘).appendTo(form);
 39             }
 40         }
 41         var oldElement = jQuery(‘#‘ + fileElementId);
 42         var newElement = jQuery(oldElement).clone();
 43         jQuery(oldElement).attr(‘id‘, fileId);
 44         jQuery(oldElement).before(newElement);
 45         jQuery(oldElement).appendTo(form);
 46
 47
 48
 49         //set attributes
 50         jQuery(form).css(‘position‘, ‘absolute‘);
 51         jQuery(form).css(‘top‘, ‘-1200px‘);
 52         jQuery(form).css(‘left‘, ‘-1200px‘);
 53         jQuery(form).appendTo(‘body‘);
 54         return form;
 55     },
 56
 57     ajaxFileUpload: function (s) {
 58         // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
 59         s = jQuery.extend({}, jQuery.ajaxSettings, s);
 60         var id = new Date().getTime()
 61         var form = jQuery.createUploadForm(id, s.fileElementId, (typeof (s.data) == ‘undefined‘ ? false : s.data));
 62         var io = jQuery.createUploadIframe(id, s.secureuri);
 63         var frameId = ‘jUploadFrame‘ + id;
 64         var formId = ‘jUploadForm‘ + id;
 65         // Watch for a new set of requests
 66         if (s.global && !jQuery.active++) {
 67             jQuery.event.trigger("ajaxStart");
 68         }
 69         var requestDone = false;
 70         // Create the request object
 71         var xml = {}
 72         if (s.global)
 73             jQuery.event.trigger("ajaxSend", [xml, s]);
 74         // Wait for a response to come back
 75         var uploadCallback = function (isTimeout) {
 76             var io = document.getElementById(frameId);
 77             try {
 78                 if (io.contentWindow) {
 79                     xml.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.innerHTML : null;
 80                     xml.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument : io.contentWindow.document;
 81
 82                 } else if (io.contentDocument) {
 83                     xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML : null;
 84                     xml.responseXML = io.contentDocument.document.XMLDocument ? io.contentDocument.document.XMLDocument : io.contentDocument.document;
 85                 }
 86             } catch (e) {
 87                 debugger;
 88                 jQuery.handleError(s, xml, null, e);
 89             }
 90             if (xml || isTimeout == "timeout") {
 91                 requestDone = true;
 92                 var status;
 93                 try {
 94                     status = isTimeout != "timeout" ? "success" : "error";
 95                     // Make sure that the request was successful or notmodified
 96                     if (status != "error") {
 97                         // process the data (runs the xml through httpData regardless of callback)
 98                         var data = jQuery.uploadHttpData(xml, s.dataType);
 99                         // If a local callback was specified, fire it and pass it the data
100                         if (s.success)
101                             s.success(data, status);
102
103                         // Fire the global callback
104                         if (s.global)
105                             jQuery.event.trigger("ajaxSuccess", [xml, s]);
106                     } else
107                         jQuery.handleError(s, xml, status);
108                 } catch (e) {
109                     status = "error";
110                     jQuery.handleError(s, xml, status, e);
111                 }
112
113                 // The request was completed
114                 if (s.global)
115                     jQuery.event.trigger("ajaxComplete", [xml, s]);
116
117                 // Handle the global AJAX counter
118                 if (s.global && ! --jQuery.active)
119                     jQuery.event.trigger("ajaxStop");
120
121                 // Process result
122                 if (s.complete)
123                     s.complete(xml, status);
124
125                 jQuery(io).unbind()
126
127                 setTimeout(function () {
128                     try {
129                         jQuery(io).remove();
130                         jQuery(form).remove();
131
132                     } catch (e) {
133                         jQuery.handleError(s, xml, null, e);
134                     }
135
136                 }, 100)
137
138                 xml = null
139
140             }
141         }
142         // Timeout checker
143         if (s.timeout > 0) {
144             setTimeout(function () {
145                 // Check to see if the request is still happening
146                 if (!requestDone) uploadCallback("timeout");
147             }, s.timeout);
148         }
149         try {
150
151             var form = jQuery(‘#‘ + formId);
152             jQuery(form).attr(‘action‘, s.url);
153             jQuery(form).attr(‘method‘, ‘POST‘);
154             jQuery(form).attr(‘target‘, frameId);
155             if (form.encoding) {
156                 jQuery(form).attr(‘encoding‘, ‘multipart/form-data‘);
157             }
158             else {
159                 jQuery(form).attr(‘enctype‘, ‘multipart/form-data‘);
160             }
161             jQuery(form).submit();
162
163         } catch (e) {
164             jQuery.handleError(s, xml, null, e);
165         }
166
167         jQuery(‘#‘ + frameId).load(uploadCallback);
168         return { abort: function () { } };
169
170     },
171
172     uploadHttpData: function (r, type) {
173         var data = !type;
174         data = type == "xml" || data ? r.responseXML : r.responseText;
175         // If the type is "script", eval it in global context
176         if (type == "script")
177             jQuery.globalEval(data);
178         // Get the JavaScript object, if JSON is used.
179         if (type == "json")
180             eval("data = " + data);
181         // evaluate scripts within html
182         if (type == "html")
183             jQuery("<div>").html(data).evalScripts();
184
185         return data;
186     }
187 })

html代码:

1  <input type="text" id="txt_file" name="txt_file" class="inputstyle" readonly style="width: 70%" />
2                                     <input type="button" id="btn_upload" name="btn_upload" class="btn_upload" value="选择文件" />
3                                     <input type="file" id="file_Excel" name="file_Excel" class="filestyle" style="width: 90%; display: none;" onchange="ajaxFileUpload();" />

js代码:

 1 $(function(){
 2     $("body").delegate("#btn_upload", "click", function () {        $("#file_Excel").trigger("click");       }); 5  });
 6
 7
 8 function ajaxFileUpload() {
 9     //        var filename = getFilePath($("#file_Excel").get(0));   // 本来在网上找了一个获取file路径的方法,但是好像都不怎么管用,最后还是直接取value值了
10     var filename = $("#file_Excel").val();
11     var suffix = filename.substring(filename.lastIndexOf(‘.‘), filename.length - 1);
12     if (filename == ‘‘ || filename == undefined) {
13         alert(‘请选择需要上传的文件!‘);
14         return false;
15     }
16     if (suffix != ‘.xls‘ && suffix != ‘.xlsx‘ && suffix != ‘.csv‘) {
17         alert(‘请选择正确的文件格式(.xls|.xlsx|.csv)!‘);
18         return false;
19     }
20     $("#txt_file").val(filename);
21
22     $.ajaxFileUpload({
23         url: ‘../ASHX/BBISExcelImportSample.ashx‘, // 请求URL地址24         type: ‘POST‘,
25         data: {
26             type: ‘getExcelInfo‘,
 29             rnd: Math.random().toString()
30         },  // 自定义参数31         secureuri: false,  // 默认false32         fileElementId: ‘file_Excel‘,  // 页面上file控件的ID,控件要有name属性33         dataType: ‘JSON‘,    // 请求成功之后返回的数据格式34         success: function (data) {   // 请求成功之后回调函数
35                     },
36         error: function (XMLHttpRequest, textStatus, errorTHrown) {// 请求报错之后执行
37         }
38     });
39 }

C#代码:

 1 public void ProcessRequest(HttpContext context)
 2         {
 3             string result = string.Empty;
 4             if (!String.IsNullOrEmpty(context.Request.Form["type"]))
 5             {
 6                 string type = context.Request.Form["type"];
 7                 switch (type)
 8                 {
 9                     case "getExcelInfo":
10                         result = GetExcelInfo();
11                         break;
12                     default:
13                         break;
14                 }
15             }
16             context.Response.Write(result);
17             context.Response.End();
18         }
19
20
21 #region 获取EXCEL相关信息
22         private string GetExcelInfo()
23         {
24             string result = string.Empty;
25             result = "{";
26             HttpFileCollection files = HttpContext.Current.Request.Files;
27             string filename = files[0].FileName;
28             string sheetName = HttpContext.Current.Request.Form["sheetName"];
29             string template_id = HttpContext.Current.Request.Form["template_id"];
30
31             WebApp.DataTableRenderToExcel.FilePath = filename;
32             WebApp.DataTableRenderToExcel.SheetName = sheetName;
33             // 获取工作簿Sheet集合
34             List<string> sheetList = WebApp.DataTableRenderToExcel.ExcelSheetToDT();
35             // 获取EXCEL表头
36             DataTable dt_columns = WebApp.DataTableRenderToExcel.GetExcelHeader();
37             // 获取EXCEL数据
38             DataTable dt_data = WebApp.DataTableRenderToExcel.GetExcelData();
39             result += "\"sheet\":" + JsonConvert.SerializeObject(sheetList);
40             result += ",\"columns\":" + JsonConvert.SerializeObject(dt_columns);
41             result += ",\"excelData\":" + JsonConvert.SerializeObject(dt_data);
42             if (sheetList != null) sheetList = null;
43             if (dt_columns != null) dt_columns.Dispose();
44             if (dt_columns != null) dt_columns = null;
45             if (dt_data != null) dt_data.Dispose();
46             if (dt_data != null) dt_data = null;
47
48             result += "}";
49             return result;
50         }
51         #endregion

记录下来,一是为了方便下次使用,另外也希望对大家有所帮助。。

时间: 2024-08-08 01:27:31

ajaxfileupload 上传插件的相关文章

jquery之ajaxfileupload异步上传插件

来自:http://www.blogjava.net/sxyx2008/archive/2010/11/02/336826.html 由于项目需求,在处理文件上传时需要使用到文件的异步上传.这里使用Jquery Ajax File Uploader这个组件下载地址:http://www.phpletter.com/download_project_version.php?version_id=6服务器端采用struts2来处理文件上传.所需环境:jquery.jsajaxfileupload.j

基于struts2的ajaxfileupload异步上传插件的使用

实例: jsp页面 <%@ page language="java" contentType="text/html" pageEncoding="UTF-8"%> <%@ taglib uri="/struts-tags" prefix="s"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//E

ajaxFileUpload上传文件成功后却无法解析服务器返回的json数据

ajaxFileUpload是一款很好用的文件上传插件,网上也有很多关于它的版本,但在上传文件成功后想返回json数据给前台时,却会出现无法解析json数据的情况. 仔细调试发现其实在向服务器提交数据后,是进入了success回调函数的,只是没有解析到json数据.那就说明服务器做出了响应的,进入了success方法的,唯一的问题就是前台接受的数据不是json格式的. 使用console.log输出data发现并不是纯粹的json数据,其中头部多了<pre style="word-wrap

(ajaxfileupload)ajaxfileupload 上传时会出现连接重置的问题

1.ajaxfileupload 上传时会出现如下问题: 2. 网上有很多的解决办法,在这里,我又发现了一种,可能你的错误会是这个原因引起的 ------原因是 : 你在一般处理程序中没有返回前台需要的数据格式字符串 3.下面给出一个例子: 1 前台: 2 <style type="text/css"> 3 .fileLink{position: relative;display: inline-block;background: #fff;border: 1px soli

用ajaxFileUpLoad上传文件不能正确取得返回值的问题

刚开始没有觉得ajax请求的dataType参数的重要性,用了ajaxFileUpLoad插件后,如果页面代码如下: fileElementId : ['imageToUpload'], url : 'url', dataType : 'json', 返回类型为json数据,那么后台处理上传后,必须将返回值封装成json格式的数据返回给前台页面. 后台封装如下: return "{\"result\":" + "\"OK\"}"

CKeditor七牛云JS SDK前端上传插件修改

七牛云官方有放出JS SDK,没有我想使用的CKeditor前端上传插件,所以结合七牛官方的Javascript SDK对CKeditor做了一些修改使它能够直接上传到七牛云,又同时保留了上传到本地服务的接口. 优点和缺点1.在前端上传到七牛云,不消耗服务器带宽和流量.空间.2.保留了CKeditor上传到自己服务器的能力.3.支持拖拽和剪切板黏贴图片上传(因为是保存为png格式,建议只黏贴色彩单调的图片,要不然图片会很大,浪费流量).4.拖拽和剪切板黏贴图片.不支持4M以上的文件,因为没有分块

SWFUpload批量上传插件

SWFUpload是一个批量上传插件,在HTML4.1里面,估计也只有Flash+javascript配合才能够做到了.先复制个重要的网址,这个应该是官方的文档了,相当齐全. http://leeon.me/upload/other/swfupload.html#uploadStart 这个是格式比较好看的. http://www.cnblogs.com/2050/archive/2012/08/29/2662932.html 算了,这个文档的内容太多,各种属性各种方法,记不了这么多,直接贴上个

jQuery上传插件Uploadify出现Http Error 302错误解决

前段时间介绍过jquery uploadify上传插件的使用方法,我在使用中遇到过Http Error 302错误问题,应该会有很多人在使用中遇到过,在此记录下来: 首 先http 302是请求被重定向的意思,这就很容易理解了,如果你的uploadify处理上传脚本有session验证,就会出现此错误,因为flash在执行 post请求的时候没有包含cookie信息,而服务器的session会根据客户端的cookie来得到SESSIONID.没有提交cookie自然 就不能获取到session,

Jquery自定义图片上传插件

1 概述 编写后台网站程序大多数用到文件上传,可是传统的文件上传控件不是外观不够优雅,就是性能不太好看,翻阅众多文件上传控件的文章,发现可以这样去定义一个文件上传控件,实现的文件上传的效果图如下: 2.该图片上传插件实现功能如下: 1>能够异步上传,上传成功之后,服务器返回响应结果:能够定义上传前和上传后自定义处理方式: 2>能够实现文件格式判断,过滤非图片文件: 3>服务端能够过滤重复上传的图片: 3.页面代码分析: 1>.Jquery图片上传插件代码如下: // 选中文件, 提