public void UploadFile(object sender , EventArgs E) { //检查上传文件不为空 if(myFile.PostedFile!=null) { string nam = myFile.PostedFile.FileName ; //取得文件名(抱括路径)里最后一个"."的索引 int i= nam.LastIndexOf("."); //取得文件扩展名 string newext =nam.Substring(i); //这里我自动根据日期和文件大小不同为文件命名,确保文件名不重复 DateTime now = DateTime.Now; string newname=now.DayOfYear.ToString()+myFile.PostedFile.ContentLength.ToString();
//保存文件到你所要的目录,这里是IIS根目录下的uploadfiles目录 //注意: 我这里用Server.MapPath()取当前文件的绝对目录.在asp.net里"/"必须用"//"代替 myFile.PostedFile.SaveAs(Server.MapPath(".//UpLoadFiles//"+newname+newext)); //得到这个文件的相关属性:文件名,文件类型,文件大小 fname.Text=myFile.PostedFile.FileName; fenc.Text=myFile.PostedFile.ContentType ; fsize.Text=myFile.PostedFile.ContentLength.ToString(); Image1.ImageUrl = "http://localhost/web/news/uploadfiles/"+newname+newext; } }
HTML页面代码
<%@ Page language="c#" Codebehind="WebForm2.aspx.cs" AutoEventWireup="false" Inherits="Web.News.WebForm2" %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" ><HTML> <HEAD> <title>WebForm2</title> <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR"> <meta content="C#" name="CODE_LANGUAGE"> <meta content="JavaScript" name="vs_defaultClientScript"> <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema"> <script language="C#" runat="server"> //This method is called when the "upload" button id pressed
</script> </HEAD> <body MS_POSITIONING="GridLayout"> <form id="Form1" method="post" runat="server"> <INPUT id="myFile" style="Z-INDEX: 101; LEFT: 408px; POSITION: absolute; TOP: 224px" type="file" name="myFile" runat="server"> <asp:button id="Button1" style="Z-INDEX: 102; LEFT: 496px; POSITION: absolute; TOP: 304px" οnclick="UploadFile" runat="server" Text="上传"></asp:button> <table cellSpacing="2" border="1"> <tr> <td><b>文件资料</b></td> <td> </td> </tr> <tr> <td>文件名 :</td> <td><asp:label id="fname" runat="server" text=""></asp:label></td> </tr> <tr> <td>文件类型 :</td> <td><asp:label id="fenc" runat="server"></asp:label></td> </tr> <tr> <td>文件大小 :(in bytes)</td> <td><asp:label id="fsize" runat="server" /></td> </tr> </table> <asp:Image id="Image1" style="Z-INDEX: 103; LEFT: 112px; POSITION: absolute; TOP: 160px" runat="server" Width="200px" Height="224px"></asp:Image> </form> </body></HTML>