/// <summary>
- /// 上传文件
- /// </summary>
- /// <param name="pf">HttpPostedFile</param>
- /// <param name="path">路径</param>
- /// <param name="filename">输出文件名</param>
- /// <returns>错误信息</returns>
- public static string UploadFile(HttpPostedFile pf,string savepath, out string filename)
- {
- string fileExt = GetFileExt(pf.FileName);
- if (!AllowFileExt(fileExt))
- {
- filename = string.Empty;
- return "上传文件扩展名不被允许";
- }
- else if (pf.ContentLength >1048576)
- {
- filename = string.Empty;
- return "上传文件大小不得超过1MB";
- }
- filename = GetNewFileName() + "." + fileExt;
- string path = HttpContext.Current.Server.MapPath("~" + "/" + savepath + "/" + filename);
- pf.SaveAs(path);
- return string.Empty;
- }
- /// <summary>
- /// 新文件名
- /// </summary>
- /// <returns></returns>
- public static string GetNewFileName()
- {
- return DateTime.Now.ToString("MMddhhmmss");
- }
- /// <summary>
- /// 取得文件扩展名
- /// </summary>
- /// <param name="filename">文件名</param>
- /// <returns>扩展名字符串</returns>
- static public string GetFileExt(string filename)
- {
- int pos = filename.LastIndexOf(".");
- return filename.Substring(pos + 1);
- }
- /// <summary>
- /// 取得文件名
- /// </summary>
- /// <param name="filename"></param>
- /// <returns>主文件名字符串</returns>
- static public string GetFileName(string filename)
- {
- int pos = filename.LastIndexOfAny(new char[] { '\\', '/' });
- int pos1 = 0;
- int len = pos - pos1;
- return filename.Substring(pos1 + 1, len);
- }
- /// <summary>
- /// 允许上传的文件类型
- /// </summary>
- /// <param name="ext">文件类型</param>
- /// <returns>是/否</returns>
- static public bool AllowFileExt(string ext)
- {
- try
- {
- string ex = "txt,xls,doc,docx,rar,zip";
- foreach (string s in ex.Split(','))
- {
- if (ext.ToLower() == s.ToLower())
- {
- return true;
- }
- }
- }
- catch { return true; }
- return false;
- }
- <asp:FileUpload ID="FileUpload1" runat="server" CssClass="fileupload" />
- //上传文件加入数据库
- protected void Button1_Click(object sender, EventArgs e)
- {
- string filename = "";
- string msg = Common .UploadFile(FileUpload1.PostedFile, "upload", out filename);
- if ("" == msg)
- {
- attendInfo.AttachUrl = filename;//成功
- return true;
- }
- else
- {
- Common.ShowMessage(""+msg+"");//失败
- return false;
- }