文件上传的应用

   /// <summary>

/// 上传文件

  1. /// </summary>
  2. /// <param name="pf">HttpPostedFile</param>
  3. /// <param name="path">路径</param>
  4. /// <param name="filename">输出文件名</param>
  5. /// <returns>错误信息</returns>
  6. publicstaticstring UploadFile(HttpPostedFile pf,string savepath, outstring filename)
  7. {
  8. string fileExt = GetFileExt(pf.FileName);
  9. if (!AllowFileExt(fileExt))
  10. {
  11. filename = string.Empty;
  12. return"上传文件扩展名不被允许";
  13. }
  14. elseif (pf.ContentLength >1048576)
  15. {
  16. filename = string.Empty;
  17. return"上传文件大小不得超过1MB";
  18. }
  19. filename = GetNewFileName() + "." + fileExt;
  20. string path = HttpContext.Current.Server.MapPath("~" + "/" + savepath + "/" + filename);
  21. pf.SaveAs(path);
  22. returnstring.Empty;
  23. }
  24. /// <summary>
  25. /// 新文件名
  26. /// </summary>
  27. /// <returns></returns>
  28. publicstaticstring GetNewFileName()
  29. {
  30. return DateTime.Now.ToString("MMddhhmmss");
  31. }
  32. /// <summary>
  33. /// 取得文件扩展名
  34. /// </summary>
  35. /// <param name="filename">文件名</param>
  36. /// <returns>扩展名字符串</returns>
  37. staticpublicstring GetFileExt(string filename)
  38. {
  39. int pos = filename.LastIndexOf(".");
  40. return filename.Substring(pos + 1);
  41. }
  42. /// <summary>
  43. /// 取得文件名
  44. /// </summary>
  45. /// <param name="filename"></param>
  46. /// <returns>主文件名字符串</returns>
  47. staticpublicstring GetFileName(string filename)
  48. {
  49. int pos = filename.LastIndexOfAny(newchar[] { '\\', '/' });
  50. int pos1 = 0;
  51. int len = pos - pos1;
  52. return filename.Substring(pos1 + 1, len);
  53. }
  54. /// <summary>
  55. /// 允许上传的文件类型
  56. /// </summary>
  57. /// <param name="ext">文件类型</param>
  58. /// <returns>是/否</returns>
  59. staticpublicbool AllowFileExt(string ext)
  60. {
  61. try
  62. {
  63. string ex = "txt,xls,doc,docx,rar,zip";
  64. foreach (string s in ex.Split(','))
  65. {
  66. if (ext.ToLower() == s.ToLower())
  67. {
  68. returntrue;
  69. }
  70. }
  71. }
  72. catch { returntrue; }
  73. returnfalse;
  74. }
  75. <asp:FileUpload ID="FileUpload1" runat="server" CssClass="fileupload" />
  76. //上传文件加入数据库
  77. protectedvoid Button1_Click(object sender, EventArgs e)
  78. {
  79. string filename = "";
  80. string msg = Common .UploadFile(FileUpload1.PostedFile, "upload", out filename);
  81. if ("" == msg)
  82. {
  83. attendInfo.AttachUrl = filename;//成功
  84. returntrue;
  85. }
  86. else
  87. {
  88. Common.ShowMessage(""+msg+"");//失败
  89. returnfalse;
  90. }
posted @ 2012-02-25 13:17  木子易  Views(212)  Comments(0Edit  收藏  举报