利用FileUpload控件轻松实现 要在工程下建立file文件夹 Default.aspx 源码 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_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>无标题页</title> </head> <body> <form id="form1" runat="server"> <div> <asp:FileUpload ID="upImage" runat="server" /> <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label><br /> <br /> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /></div> </form> </body> </html> Default.aspx.cs 源码 using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { Label1.Text = this.getimg(); } public string getimg() { HttpPostedFile myFile = upImage.PostedFile; int nFileLen = myFile.ContentLength; if (nFileLen == 0) return "没有选择上传图片"; //获取upImage选择文件的扩展名 string extendName = System.IO.Path.GetExtension(myFile.FileName).ToLower(); //判断是否为图片格式 if (extendName != ".jpg" && extendName != ".jpge" && extendName != ".gif" && extendName != ".bmp" && extendName != ".png") return "图片格式不正确"; byte[] myData = new Byte[nFileLen]; myFile.InputStream.Read(myData, 0, nFileLen); string sFilename = System.IO.Path.GetFileName(myFile.FileName); int file_append = 0; string sSavePath = "file//"; //检查当前文件夹下是否有同名图片,有则在文件名+1 while (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath(sSavePath + sFilename))) { file_append++; sFilename = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) + file_append.ToString() + extendName; } System.IO.FileStream newFile = new System.IO.FileStream(System.Web.HttpContext.Current.Server.MapPath(sSavePath + sFilename), System.IO.FileMode.Create, System.IO.FileAccess.Write); newFile.Write(myData, 0, myData.Length); newFile.Close(); return "图片上传成功"; } }