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