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" >
<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>