sunny123456

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

https://blog.csdn.net/kongwei521/article/details/52910970

Html 代码及调用方法:

  1. <!DOCTYPE html>
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head runat="server">
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  5. <title></title>
  6. </head>
  7. <body>
  8. <form id="form1" runat="server">
  9. <div style="margin:0 auto;text-align:center;">
  10. <p>
  11. <asp:Image ID="imgShow" runat="server" Width="120" Height="120" ImageUrl="~/assets/images/nophoto.gif"/>
  12. </p>
  13. <p> <input name="file" id="fUpLoad" type="file"/><input type="hidden" id="Hfurl" runat="server"/>
  14. <input type="hidden" id="hfStatus" runat="server"/></p>
  15. <p>
  16. <input type="button" value="上传" id="iUpLoad"/>
  17. </p>
  18. </div>
  19. <script src="assets/js/jquery-1.8.2.min.js"></script>
  20. <script src="plugins/uploadify/ajaxfileupload.js"></script>
  21. <script type="text/javascript">
  22. $(function () {
  23. $("#iUpLoad").click(function () {
  24. ajaxFileUpload();
  25. })
  26. })
  27. function ajaxFileUpload() {
  28. $.ajaxFileUpload
  29. (
  30. {
  31. url: 'UpLoadHeadImg.aspx?random=' + Math.random(), //用于文件上传的服务器端请求地址
  32. //secureuri: false, //一般设置为false
  33. fileElementId: 'fUpLoad', //文件上传空间的id属性 <input type="file" id="file" name="file" />
  34. dataType: 'json', //返回值类型 一般设置为json
  35. success: function (data, status) //服务器成功响应处理函数
  36. {
  37. alert(data);
  38. $("#imgShow").attr("src", data.imgurl);
  39. $("#Hfurl").val(data.imgurl); //alert($("#hfDel").val());
  40. if (typeof (data.error) != 'undefined') {
  41. if (data.error != '') {
  42. alert(data.error);
  43. } else {
  44. //alert(data.msg);
  45. }
  46. }
  47. },
  48. error: function (data, status, e)//服务器响应失败处理函数
  49. {
  50. alert(e);
  51. }
  52. }
  53. )
  54. return false;
  55. }
  56. </script>
  57. <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
  58. </form>
  59. </body>
  60. </html>

后台代码:

  1. protected void Page_Load(object sender, EventArgs e)
  2. {
  3. log4net.ILog log = log4net.LogManager.GetLogger(this.GetType().Name);
  4. int count = Request.Files.Count;
  5. string res = string.Empty;
  6. string error = string.Empty;
  7. string imgurl = string.Empty; ;
  8. if (count > 0)
  9. {
  10. try
  11. {
  12. HttpPostedFile File1 = Request.Files[0];
  13. string suffix = Path.GetExtension(File1.FileName).ToLower();
  14. string path = Server.MapPath("UpLoadImg/HeadImage"); //用来生成文件夹
  15. if (File1.ContentLength / 4096 > 4096)
  16. {
  17. error = "单张头像不能超过4096K(4M),请重新选择头像上传。";
  18. }
  19. else
  20. {
  21. if (!Directory.Exists(path))
  22. Directory.CreateDirectory(path);
  23. var savepath = "UpLoadImg/HeadImage/" + Guid.NewGuid() + suffix;
  24. if (suffix.Equals(".jpg") || suffix.Equals(".png") || suffix.Equals(".gif") || suffix.Equals(".jpeg"))
  25. {
  26. File1.SaveAs(Server.MapPath(savepath));
  27. }
  28. imgShow.ImageUrl = savepath; imgurl = savepath;
  29. hfStatus.Value = "1"; Hfurl.Value = savepath;
  30. error = "上传成功";
  31. res = "{\"info\":\"" + error + "\",\"data\":\"1\",\"imgurl\":\"" + savepath + "\"}";
  32. }
  33. if (HttpContext.Current.Request.Cookies["UserLogin"] != null)
  34. {
  35. log.Info(new LogContent(SearchDataClass.GetIPAddress(),
  36. HttpContext.Current.Request.Cookies["UserLogin"]["ClientName"],
  37. "上传头像图片信息", "上传图片为" + File1.FileName + "的图片路径" + imgurl + "成功,信息为。" + res));
  38. }
  39. else
  40. {
  41. log.Info(new LogContent(SearchDataClass.GetIPAddress(), "system",
  42. "上传头像图片信息", "上传图片为" + File1.FileName + "的图片路径" + imgurl + "成功,信息为。" + res));
  43. }
  44. }
  45. catch (Exception ex)
  46. {
  47. hfStatus.Value = "0";
  48. res = "{\"info\":\"" + ex.Message + "\",\"data\":\"0\",\"imgurl\":\"\"}";
  49. if (HttpContext.Current.Request.Cookies["UserLogin"] != null)
  50. {
  51. log.Fatal(new LogContent(SearchDataClass.GetIPAddress(),
  52.  HttpContext.Current.Request.Cookies["UserLogin"]["ClientName"], "上传头像图片信息", res));
  53. }
  54. else
  55. {
  56. log.Fatal(new LogContent(SearchDataClass.GetIPAddress(), "system",
  57. "上传头像图片信息", res));
  58. }
  59. }
  60. Response.Write(res);
  61. Response.End();
  62. }
  63. else
  64. {
  65. if (HttpContext.Current.Request.Cookies["UserLogin"] != null)
  66. {
  67. log.Warn(new LogContent(SearchDataClass.GetIPAddress(),
  68. HttpContext.Current.Request.Cookies["UserLogin"]["ClientName"], "上传头像图片信息", "无上传头像图片信息。"));
  69. }
  70. else
  71. {
  72. log.Warn(new LogContent(SearchDataClass.GetIPAddress(), "system", "上传头像图片信息", "无上传头像图片信息。"));
  73. }
  74. }
  75. }

由于上传会出现错误,因此修改ajaxfileupload.js


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


posted on 2021-03-17 08:33  sunny123456  阅读(431)  评论(0编辑  收藏  举报