"> ">

Presentation is loading. Please wait.

Presentation is loading. Please wait.

客戶端的檔案上傳 HtmlInputFile檔案控制項 上傳單一檔案 同時上傳多個檔案.

Similar presentations


Presentation on theme: "客戶端的檔案上傳 HtmlInputFile檔案控制項 上傳單一檔案 同時上傳多個檔案."— Presentation transcript:

1 客戶端的檔案上傳 HtmlInputFile檔案控制項 上傳單一檔案 同時上傳多個檔案

2 11-2-1 HtmlInputFile檔案控制項-標籤
ASP.NET的Web表單可以使用HTML控制項的HtmlInputFile檔案控制項瀏覽客戶端的檔案清單,即在客戶端選擇上傳檔案,基本語法如下所示: <input type="FILE" Id="field_name" size="number" accept="image/*" Runat="server"/>

3 11-2-1 HtmlInputFile檔案控制項-enctype屬性
因為HtmlInputFile控制項的主要目的是選擇上傳檔案,所以在Web表單<form>標籤需要使用enctype屬性來指定編碼方式,如下所示: <form enctype="multipart/form-data“ Runat="server"> ………….. </form> 上述enctype屬性指定上傳檔案的編碼方式。

4 11-2-2 上傳單一檔案-取得HttpPostedFile物件
在ASP.NET程式上傳檔案是使用System.IO名稱空間的HttpPostedFile類別,所以需要先匯入此名稱空間,如下所示: Import Namespace="System.IO" %> 在Web表單的HtmlInputFile控制項選好上傳檔案,上傳檔案資料就會隨著網頁內容送回伺服端,ASP.NET程式可以使用控制項的PostedFile屬性來取得HttpPostedFile物件,如下所示: HttpPostedFile file = filename.PostedFile;

5 上傳單一檔案-儲存上傳檔案 HttpPostedFile物件可以使用此物件的SaveAs()方法將資料寫成伺服端檔案,完成檔案上傳,如下所示: file.SaveAs(uploadPath + "\\" + Path.GetFileName(file.FileName)); 上述方法參數是伺服端檔案的實際路徑,FileName屬性取得上傳檔案名稱,ContentLength屬性取得上傳檔案長度,Path類別的GetFileName()方法可以取得路徑中的檔案名稱。

6 範例(使用asp控制項FileUpload)
<body> <form id="form1" runat="server"> <div> <asp:FileUpload ID="FileUpload1" runat="server" /><br /> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /> </div> </form> </body>

7 範例 using System.IO; protected void Button1_Click(object sender, EventArgs e) { string uploadpath=Server.MapPath("image"); HttpPostedFile file = FileUpload1.PostedFile; file.SaveAs(uploadpath + "\\" + Path.GetFileName(file.FileName)); }

8 11-2-3 同時上傳多個檔案-取得HttpFileCollection物件
在Web表單如果擁有多個HtmlInputFile控制項,ASP.NET程式就可以同時上傳多個檔案,在選擇好多個上傳檔案後,程式可以取得這些檔案的集合物件,如下所示: HttpFileCollection objFileCollection = Request.Files; 上述程式碼使用Request物件的Files屬性取得上傳檔案的HttpFileCollection物件,這就是HttpPostedFile的集合物件。

9 11-2-3 同時上傳多個檔案-取得每一個HttpPostedFile物件
在取得上傳檔案的集合物件後,可以使用for迴圈取得每一個HttpPostedFile物件,如下所示: for (i = 0; i < objFileCollection.Count; i++) { file = objFileCollection[i]; if (file.ContentLength != 0) { file.SaveAs(uploadPath + "\\" + Path.GetFileName(file.FileName)); counter = counter + 1; }

10 範例 <body> <form id="form1" runat="server"> <div>
<asp:FileUpload ID="FileUpload1" runat="server" /><br />  <asp:FileUpload ID="FileUpload2" runat="server" /> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /></div> </form> </body>

11 範例 protected void Button1_Click(object sender, EventArgs e) {
string uploadpath = Server.MapPath("image"); HttpFileCollection files = Request.Files; int i; for (i=0;i<files.Count;i++){ files[i].SaveAs(uploadpath+"\\"+Path.GetFileName(files[i].FileName)); }


Download ppt "客戶端的檔案上傳 HtmlInputFile檔案控制項 上傳單一檔案 同時上傳多個檔案."

Similar presentations


Ads by Google