ASP.NET 图片上传-简单实用(VS2008 FileUpload控件+ASP.NET2.0)按时间+三位随机数重命名2009年07月08日 星期三 上午 08:55近期公司asp网站要向asp.net网站过渡,苦于没有一个简单实用的图片上传模块,于是自己参考网上资料写了一个,希望与喜欢asp.net的朋友共同进步。 上传文件被自动放到文件夹“UpFiles/年月”下面,没有会自动创建。 Default.aspx文件: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="FileUpload._Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>图片上传(VS2008 FileUpload控件+ASP.NET2.0)</title> </head> <body> <form id="form1" runat="server"> <div> <asp:FileUpload ID="ImgFileUpload" runat="server" /> <asp:Button ID="btnFileUpload" runat="server" onclick="btnFileUpload_Click" Text="上传" /><br /> <asp:Label ID="lblMsg" runat="server" Text=""></asp:Label> </div> </form> </body> </html> Default.aspx.cs文件: using System; using System.Collections; using System.Configuration; using System.Data; using System.IO; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; namespace FileUpload { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnFileUpload_Click(object sender, EventArgs e) { UploadPicFile(ImgFileUpload); } internal readonly string AllowExt = "jpe|jpeg|jpg|png|tif|tiff|bmp|gif|wbmp|swf|psd"; /// <summary> /// 检测扩展名的有效性 /// </summary> /// <param name="sExt">文件名扩展名</param> /// <returns>如果扩展名有效,返回true,否则返回false.</returns> bool CheckValidExt(string sExt) { bool flag = false; string[] aExt = AllowExt.Split('|'); foreach (string filetype in aExt) { if (filetype.ToLower() == sExt.Replace(".", "")) { flag = true; break; } } return flag; } private void UploadPicFile(System.Web.UI.WebControls.FileUpload Fupload) { //文件上传函数 try { if (Fupload.HasFile) { //判断文件格式 string sExt = Fupload.FileName.Substring(Fupload.FileName.LastIndexOf(".")).ToLower(); if (!CheckValidExt(sExt)) { lblMsg.Text = "(原图片文件格式不正确!支持的格式有[ " + AllowExt + " ])"; return; } //判断文件大小 int intFileLength = Fupload.PostedFile.ContentLength; if (intFileLength > 1000 * 1000) { this.lblMsg.Text = "文件大于1M,不能上传!"; return; } Random ran = new Random(); string UpDir = "/UpFiles/" + DateTime.Now.ToString("yyyyMM"); //上传目录 if (!Directory.Exists(Server.MapPath(UpDir))) { Directory.CreateDirectory(Server.MapPath(UpDir)); if (!Directory.Exists(Server.MapPath(UpDir))) return; //如果创建失败则返回 } //上传文件重命名:时间+三位随机数 string fileName = UpDir + "/" + DateTime.Now.ToString("yyyyMMddhhmmssfff") + Convert.ToString(ran.Next(100, 999)); fileName = fileName + sExt; Fupload.PostedFile.SaveAs(HttpContext.Current.Server.MapPath(fileName)); lblMsg.Text = fileName + "上传成功!"; } else lblMsg.Text = "请选择文件!"; return; } catch { lblMsg.Text = "发生错误,请重新上传文件!"; } } } } |