asp.net实现文件上传带进度条(多种风格)

柔光的暖阳◎ 2022-08-26 11:15 368阅读 0赞

文件上传 带进度条 多种风格 非常漂亮!

asp.net实现文件上传带进度条(多种风格)

0_1274326725mk2m.gif

0_12743267345554.gif

0_12743267391nBZ.gif

0_12743267808860.gif

友好的提示 以及上传验证!

0_1274326802Do5Z.gif

0_1274326805EP9D.gif

0_1274326809ZIZG.gif

0_1274326812vTWp.gif

部分代码:

[c-sharp] view plain copy

  1. <%@ Page Language=”C#“ %>
  2. <%@ Register Assembly=”MattBerseth.WebControls.AJAX” Namespace=”MattBerseth.WebControls.AJAX.Progress” TagPrefix=”mb” %>
  3. <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  4. Untitled Page
  5. <!—
  6. BODY{ font-family:Arial, Sans-Serif; font-size:12px;}
  7. -->
  8. <!—
  9. protected void Page_Load(object sender, EventArgs args)
  10. {
  11. if (!this.IsPostBack)
  12. {
  13. this.Session[“UploadInfo”] = new UploadInfo { IsReady = false };
  14. }
  15. }
  16. ///
  17. ///
  18. ///
  19. [System.Web.Services.WebMethod]
  20. [System.Web.Script.Services.ScriptMethod]
  21. public static object GetUploadStatus()
  22. {
  23. //获取文件长度
  24. UploadInfo info = HttpContext.Current.Session[“UploadInfo”] as UploadInfo;
  25. if (info != null && info.IsReady)
  26. {
  27. int soFar = info.UploadedLength;
  28. int total = info.ContentLength;
  29. int percentComplete = (int)Math.Ceiling((double)soFar / (double)total * 100);
  30. string message = string.Format(“上传 {0} … {1} of {2} 字节”, info.FileName, soFar, total);
  31. // 返回百分比
  32. return new { percentComplete = percentComplete, message = message };
  33. }
  34. // 还没有准备好…
  35. return null;
  36. }
  37. // —>
  38. <!—
  39. var intervalID = 0;
  40. var progressBar;
  41. var fileUpload;
  42. var form;
  43. // 进度条
  44. function pageLoad(){
  45. $addHandler($get(‘upload’), ‘click’, onUploadClick);
  46. progressBar = $find(‘progress’);
  47. }
  48. // 注册表单
  49. function register(form, fileUpload){
  50. this.form = form;
  51. this.fileUpload = fileUpload;
  52. }
  53. //上传验证
  54. function onUploadClick() {
  55. var vaild = fileUpload.value.length > 0;
  56. if(vaild){
  57. $get(‘upload’).disabled = ‘disabled’;
  58. updateMessage(‘info’, ‘初始化上传…’);
  59. //提交上传
  60. form.submit();
  61. // 隐藏frame
  62. Sys.UI.DomElement.addCssClass($get(‘uploadFrame’), ‘hidden’);
  63. // 0开始显示进度条
  64. progressBar.set_percentage(0);
  65. progressBar.show();
  66. // 上传过程
  67. intervalID = window.setInterval(function(){
  68. PageMethods.GetUploadStatus(function(result){
  69. if(result){
  70. // 更新进度条为新值
  71. progressBar.set_percentage(result.percentComplete);
  72. //更新信息
  73. updateMessage(‘info’, result.message);
  74. if(result == 100){
  75. // 自动消失
  76. window.clearInterval(intervalID);
  77. }
  78. }
  79. });
  80. }, 500);
  81. }
  82. else{
  83. onComplete(‘error’, ‘您必需选择一个文件’);
  84. }
  85. }
  86. function onComplete(type, msg){
  87. // 自动消失
  88. window.clearInterval(intervalID);
  89. // 显示消息
  90. updateMessage(type, msg);
  91. // 隐藏进度条
  92. progressBar.hide();
  93. progressBar.set_percentage(0);
  94. // 重新启用按钮
  95. $get(‘upload’).disabled = ‘’;
  96. // 显示frame
  97. Sys.UI.DomElement.removeCssClass($get(‘uploadFrame’), ‘hidden’);
  98. }
  99. function updateMessage(type, value){
  100. var status = $get(‘status’);
  101. status.innerHTML = value;
  102. // 移除样式
  103. status.className = ‘’;
  104. Sys.UI.DomElement.addCssClass(status, type);
  105. }
  106. // —>
  107. 文件上传

  108. 请选择要上传的文件

upload.aspx:

[c-sharp] view plain copy

  1. //限制大小 1M
  2. protected void Page_Load2(object sender, EventArgs e)
  3. {
  4. if (this.IsPostBack)
  5. {
  6. UploadInfo uploadInfo = this.Session[“UploadInfo”] as UploadInfo;
  7. if (uploadInfo == null)
  8. {
  9. // 让父页面知道无法处理上传
  10. const string js = “window.parent.onComplete(‘error’, ‘无法上传文件。请刷新页面,然后再试一次);”;
  11. ScriptManager.RegisterStartupScript(this, typeof(upload_aspx), “progress”, js, true);
  12. }
  13. else
  14. {
  15. // 让服务端知道我们还没有准备好..
  16. uploadInfo.IsReady = false;
  17. // 上传验证
  18. if (this.fileUpload.PostedFile != null && this.fileUpload.PostedFile.ContentLength > 0
  19. && this.fileUpload.PostedFile.ContentLength < 1048576)// 限制1M
  20. {
  21. // 设置路径
  22. string path = this.Server.MapPath(@”Uploads”);
  23. string fileName = Path.GetFileName(this.fileUpload.PostedFile.FileName);
  24. // 上传信息
  25. uploadInfo.ContentLength = this.fileUpload.PostedFile.ContentLength;
  26. uploadInfo.FileName = fileName;
  27. uploadInfo.UploadedLength = 0;
  28. //文件存在 初始化…
  29. uploadInfo.IsReady = true;
  30. //缓存
  31. int bufferSize = 1;
  32. byte[] buffer = new byte[bufferSize];
  33. // 保存字节
  34. using (FileStream fs = new FileStream(Path.Combine(path, fileName), FileMode.Create))
  35. {
  36. while (uploadInfo.UploadedLength < uploadInfo.ContentLength)
  37. {
  38. //从输入流放进缓冲区
  39. int bytes = this.fileUpload.PostedFile.InputStream.Read(buffer, 0, bufferSize);
  40. // 字节写入文件流
  41. fs.Write(buffer, 0, bytes);
  42. // 更新大小
  43. uploadInfo.UploadedLength += bytes;
  44. // 线程睡眠 上传就更慢 这样就可以看到进度条了
  45. System.Threading.Thread.Sleep(100);
  46. }
  47. }
  48. // 删除.
  49. File.Delete(Path.Combine(path, fileName));
  50. // 让父页面知道已经处理上传完毕
  51. const string js = “window.parent.onComplete(‘success’, ‘{0} 已成功上传’);”;
  52. ScriptManager.RegisterStartupScript(this, typeof(upload_aspx), “progress”, string.Format(js, fileName), true);
  53. }
  54. else
  55. {
  56. if (this.fileUpload.PostedFile.ContentLength >= 1048576)//1M
  57. {
  58. const string js = “window.parent.onComplete(‘error’, ‘超出上传文件限制大小,请重新选择’);”;
  59. ScriptManager.RegisterStartupScript(this, typeof(upload_aspx), “progress”, js, true);
  60. }
  61. else
  62. {
  63. const string js = “window.parent.onComplete(‘error’, ‘上传文件出错’);”;
  64. ScriptManager.RegisterStartupScript(this, typeof(upload_aspx), “progress”, js, true);
  65. }
  66. }
  67. uploadInfo.IsReady = false;
  68. }
  69. }
  70. }
  71. // 不限制大小
  72. protected void Page_Load(object sender, EventArgs e)
  73. {
  74. if (this.IsPostBack)
  75. {
  76. UploadInfo uploadInfo = this.Session[“UploadInfo”] as UploadInfo;
  77. uploadInfo.IsReady = false;
  78. if (this.fileUpload.PostedFile != null && this.fileUpload.PostedFile.ContentLength > 0)
  79. {
  80. string path = this.Server.MapPath(@”Uploads”);
  81. string fileName = Path.GetFileName(this.fileUpload.PostedFile.FileName);
  82. uploadInfo.ContentLength = this.fileUpload.PostedFile.ContentLength;
  83. uploadInfo.FileName = fileName;
  84. uploadInfo.UploadedLength = 0;
  85. uploadInfo.IsReady = true;
  86. int bufferSize = 1;
  87. byte[] buffer = new byte[bufferSize];
  88. using (FileStream fs = new FileStream(Path.Combine(path, fileName), FileMode.Create))
  89. {
  90. while (uploadInfo.UploadedLength < uploadInfo.ContentLength)
  91. {
  92. int bytes = this.fileUpload.PostedFile.InputStream.Read(buffer, 0, bufferSize);
  93. fs.Write(buffer, 0, bytes);
  94. uploadInfo.UploadedLength += bytes;
  95. }
  96. }
  97. const string js = “window.parent.onComplete(‘success’, ‘{0} 已成功上传’);”;
  98. ScriptManager.RegisterStartupScript(this, typeof(upload_aspx), “progress”, string.Format(js, fileName), true);
  99. }
  100. else
  101. {
  102. const string js = “window.parent.onComplete(‘error’, ‘上传文件出错’);”;
  103. ScriptManager.RegisterStartupScript(this, typeof(upload_aspx), “progress”, js, true);
  104. }
  105. uploadInfo.IsReady = false;
  106. }
  107. }

发表评论

表情:
评论列表 (有 0 条评论,368人围观)

还没有评论,来说两句吧...

相关阅读

    相关 ajax 文件进度

    一:方案分析        基于浏览器的文件上传,为了有更好的用户体验,我们一般就设置一个旋转的图标,旋转的图标无法实时的监控文件上传情况。所以我们将实现一个如何实时的监控