ajax 檔案上傳 代碼
<%@ Import Namespace="System.IO" %>
<%@ page Language="C#" debug="true" %>
<html>
<head>
<title>ajax asp.net 上傳檔案 , </title>
<script language="C#" runat="server">
//This method is called when the "upload" button id pressed
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根目錄下的upload目錄.你可以改變.
//注意: 我這裡用Server.MapPath()取當前檔案的絕對目錄.在asp.net裡"\"必須用"\\"代替
//myFile.PostedFile.SaveAs(Server.MapPath("img/"+newname+newext));
// myFile.PostedFile.SaveAs(Server.MapPath("img/" +));
//得到這個檔案的相關屬性:檔案名稱,檔案類型,檔案大小
//fname.Text=myFile.PostedFile.FileName;
//fenc.Text=myFile.PostedFile.ContentType ;
//fsize.Text=myFile.PostedFile.ContentLength.ToString();
//fsize.Text = System.IO.Path.GetFileName(nam);
string localname = System.IO.Path.GetFileName(myFile.Value);
string path = myFile.PostedFile.FileName;
myFile.PostedFile.SaveAs(Server.MapPath ("img/" + localname));
fname.Text = localname;
fenc.Text = System.IO.Path.GetExtension(path);
filepath.Text = path;
filebytes.Text = myFile.PostedFile.ContentLength.ToString();
}
}
</script>
</head>
<body>
<center>
<h3> 檔案上傳的執行個體, 來自<a href="http://www.chinabs.net">中國BS網</a></h3>
<form id="uploderform" method="post" action="FileUpload.aspx" enctype="multipart/form-data" runat="server" >
<table border="1" cellspacing="2" cellpadding="2" >
<tr> <td><h5>選擇要上傳的檔案:</h5></td></tr>
<tr>
<td>
<input type="file" id="myFile" runat="server" NAME="myFile">
</td>
</tr>
<tr><td>
<input type="button" value="上 傳" OnServerClick="UploadFile" runat="server" ID="Button1" NAME="Button1">
</td></tr>
</table>
</form>
<br>
<br>
<table border="1" cellspacing="2">
<tr><td><b>檔案資料</b></td>
<td> </td>
</tr>
<tr>
<td>檔案名稱 :</td>
<td ><asp:label id="fname" text="" runat="server" /></td></tr>
<tr>
<td>檔案類型 :</td>
<td><asp:label id="fenc" runat="server" /></td></tr>
<tr>
<td>檔案路徑 :</td>
<td><asp:label id="filepath" runat="server" /></td></tr>
<tr>
<td>檔案大小 :</td>
<td><asp:label id="filebytes" runat="server" /></td></tr>
</table>
<br>
<br>
<br>
</center>
</body>
</html>