ASP.NET有兩個控制項,允許用戶將文件上載到web伺服器。一旦伺服器接收到發布的文件數據,應用程式就可以保存、檢查或忽略它。以下控制項允許上載文件:
HtmlInputFile-一個HTML伺服器控制項
文件上載-和ASP.NET web控制項
兩個控制項都允許文件上載,但FileUpload控制項會自動設置表單的編碼,而HtmlInputFile則不會這樣做。
在本教程中,我們使用FileUpload控制項。FileUpload控制項允許用戶瀏覽並選擇要上載的文件,提供一個瀏覽按鈕和一個文本框來輸入文件名。
一旦用戶通過鍵入名稱或瀏覽在文本框中輸入了文件名,就可以調用FileUpload控制項的SaveAs方法將文件保存到磁碟。
FileUpload的基本語法是:
<asp:FileUpload ID= "Uploader" runat = "server" />
FileUpload類派生自WebControl類,並繼承其所有成員。除此之外,FileUpload類還具有以下只讀屬性:
Properties | Description |
---|---|
FileBytes | Returns an array of the bytes in a file to be uploaded. |
FileContent | Returns the stream object pointing to the file to be uploaded. |
FileName | Returns the name of the file to be uploaded. |
HasFile | Specifies whether the control has a file to upload. |
PostedFile | Returns a reference to the uploaded file. |
發布的文件封裝在HttpPostedFile類型的對象中,可以通過FileUpload類的posted file屬性訪問該對象。
HttpPostedFile類具有以下常用屬性:
Properties | Description |
---|---|
ContentLength | Returns the size of the uploaded file in bytes. |
ContentType | Returns the MIME type of the uploaded file. |
FileName | Returns the full filename. |
InputStream | Returns a stream object pointing to the uploaded file. |
Example
下面的示例演示FileUpload控制項及其屬性。表單有一個FileUpload控制項、一個save按鈕和一個label控制項,用於顯示文件名、文件類型和文件長度。
在「設計」視圖中,窗體如下所示:
內容文件代碼如下:
<body> <form id="form1" runat="server"> <div> <h3> File Upload:</h3> <br /> <asp:FileUpload ID="FileUpload1" runat="server" /> <br /><br /> <asp:Button ID="btnsave" runat="server" onclick="btnsave_Click" Text="Save" style="width:85px" /> <br /><br /> <asp:Label ID="lblmessage" runat="server" /> </div> </form> </body>
保存按鈕後面的代碼如下所示:
protected void btnsave_Click(object sender, EventArgs e) { StringBuilder sb = new StringBuilder(); if (FileUpload1.HasFile) { try { sb.AppendFormat(" Uploading file: {0}", FileUpload1.FileName); //saving the file FileUpload1.SaveAs("<c:\\SaveDirectory>" + FileUpload1.FileName); //Showing the file information sb.AppendFormat("<br/> Save As: {0}", FileUpload1.PostedFile.FileName); sb.AppendFormat("<br/> File type: {0}", FileUpload1.PostedFile.ContentType); sb.AppendFormat("<br/> File length: {0}", FileUpload1.PostedFile.ContentLength); sb.AppendFormat("<br/> File name: {0}", FileUpload1.PostedFile.FileName); }catch (Exception ex) { sb.Append("<br/> Error <br/>"); sb.AppendFormat("Unable to save file <br/> {0}", ex.Message); } } else { lblmessage.Text = sb.ToString(); } }
注意以下幾點:
StringBuilder類是從System.IO命名空間派生的,因此需要包含它。
try和catch塊用於捕獲錯誤,並顯示錯誤消息。