c# 使用ajaxfileupload上传文件,通过一般处理程序(Handler)接收文件 ashx 图片 Excel文件都可以

时间:2021-03-17 15:09:53   收藏:0   阅读:0

https://blog.csdn.net/sinat_16998945/article/details/81125950

界面如下图:

技术图片HTML代码如下:

  1. <html >
  2. <head >
  3. <!-- 引入jquery ajaxfileupload.js -->
  4. <!-- ajaxfileupload.js 为了兼容IE不同版本,需要修改源代码,文章附带源代码 -->
  5. <script src="../../Content/js/jquery/jquery-1.4.2.min.js" type="text/javascript"></script>
  6. <script src="../../Content/js/ajaxfileupload.js" type="text/javascript"></script>
  7. </head>
  8. <body>
  9. <div>
  10. <div>
  11. <input type="file" id="fileExcel" name="fileExcel" />
  12. <a onclick="ajaxFileUpload()" href="javascript:void(0);" >上传</a>
  13. </div>
  14. </div>
  15. </body>
  16. <script type="text/javascript">
  17. function ajaxFileUpload() {
  18. try {
  19. $.ajaxFileUpload({
  20. url: ‘../../AjaxHandler/SIMManage/SIMInfoHandler.ashx?action=UpFile‘, //用于文件上传的服务器端请求地址
  21. secureuri: false, //是否需要安全协议,一般设置为false
  22. fileElementId: ‘fileExcel‘, //文件上传域的ID
  23. dataType: ‘json‘, //返回值类型 一般设置为json
  24. success: function (data, status) //服务器成功响应处理函数
  25. {
  26. //上传成功
  27. },
  28. error: function (data, status, e)//服务器响应失败处理函数
  29. {
  30. alert(e);
  31. }
  32. })
  33. } catch (e) {
  34. alert(e.Message)
  35. }
  36. return false;
  37. }
  38. </script>
  39. </html>

ajaxfileupload源代码修改如下:

        //      源代码
        //        if(window.ActiveXObject) {
        //            var io = document.createElement(‘<iframe id="‘ + frameId + ‘" name="‘ + frameId + ‘" />‘);
        //            if(typeof uri== ‘boolean‘){
        //                io.src = ‘javascript:false‘;
        //            }
        //            else if(typeof uri== ‘string‘){
        //                io.src = uri;
        //            }
        //        }else {
        //            var io = document.createElement(‘iframe‘);
        //           io.id = frameId;
        //            io.name = frameId;
        //        }

        //修改源代码,参考网上大神修改内容
        if (window.ActiveXObject) {
            if (jQuery.browser.version == "9.0" || jQuery.browser.version == "10.0") {
                var io = document.createElement(‘iframe‘);
                io.id = frameId;
                io.name = frameId;
            } else if (jQuery.browser.version == "6.0" || jQuery.browser.version == "7.0" || jQuery.browser.version == "8.0") {
                var io = document.createElement(‘<iframe id="‘ + frameId + ‘" name="‘ + frameId + ‘" />‘);
                if (typeof uri == ‘boolean‘) {
                    io.src = ‘javascript:false‘;
                }
                else if (typeof uri == ‘string‘) {
                    io.src = uri;
                }
            }

        }
        else {
            var io = document.createElement(‘iframe‘);
            io.id = frameId;
            io.name = frameId;
        }

 

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

 

一般处理程序(Handler)接收文件代码如下

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.SessionState;
  6. using System.IO;
  7. namespace Web.AjaxHandler.SIMManage
  8. {
  9. /// <summary>
  10. /// SIMInfoHandler 的摘要说明
  11. /// </summary>
  12. public class SIMInfoHandler : IHttpHandler
  13. {
  14. HttpRequest Request;
  15. HttpResponse Response;
  16. public void ProcessRequest(HttpContext context)
  17. {
  18. context.Response.ContentType = "text/plain";
  19. Request = context.Request;
  20. Response = context.Response;
  21. string action = Request.QueryString["action"];
  22. switch (action)
  23. {
  24. case "UpFile":
  25. UpFile();
  26. break;
  27. }
  28. }
  29. private void UpFile()
  30. {
  31. HttpFileCollection files = Request.Files;
  32. string msg = string.Empty;
  33. string error = string.Empty;
  34. string res = string.Empty;
  35. try
  36. {
  37. string filename = System.IO.Path.GetFileName(files[0].FileName);
  38. //判断是否有文件
  39. if (filename == "")
  40. {
  41. Response.Write("上传文件为空,请选择上传文件格式为‘.xls‘的文件。");
  42. return;
  43. }
  44. string [] strArrary = filename.Split(‘.‘);
  45. //判断文件格式
  46. if (strArrary.LastOrDefault() != "xls" && strArrary.LastOrDefault() != "xlsx")
  47. {
  48. Response.Write("上传文件格式不正确,请选择上传文件格式为‘.xls‘或‘.xlsx‘的文件。");
  49. return;
  50. }
  51. //存放文件
  52. if (Directory.Exists(HttpContext.Current.Server.MapPath("~/Document/TemporaryDocuments")) == false)//如果不存在就创建file文件夹
  53. {
  54. Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/Document/TemporaryDocuments"));
  55. }
  56. string url = "~/Document/TemporaryDocuments/" + filename;
  57. string path = HttpContext.Current.Server.MapPath(url);
  58. files[0].SaveAs(path);
  59. Response.Write("上传文件成功");
  60. return;
  61. }
  62. catch (Exception ex)
  63. {
  64. }
  65. }
  66. public bool IsReusable
  67. {
  68. get
  69. {
  70. return false;
  71. }
  72. }
  73. }
  74. }

技术图片

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!