顯示一個文本框控件和一個浏覽按鈕,使使用者可以選擇要上載到伺服器的檔案。 <b>命名空間:</b> System.Web.UI.WebControls
<b>程式集:</b> System.Web(在 system.web.dll 中)
執行個體:
html代碼:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="inputfile._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>無标題頁</title>
<script language="javascript" type="text/javascript">
// <!CDATA[
// ]]>
</script>
<style type="text/css">
.style1
{
text-align: center;
}
#form1
</style>
</head>
<body>
<form id="form1" runat="server" method="post" enctype="multipart/form-data">
<div style="position:static;">
<div class="style1">
示範檔案上傳控件
</div>
<hr style="width:80%" />
<asp:FileUpload ID="File1" runat="server"/>
<asp:Button ID="UploadBtn" runat="server" onclick="Button1_Click" Text="上傳" />
</div>
<asp:Label ID="Label1" runat="server"
Width="437px" Height="61px"></asp:Label>
</form>
</body>
</html>
背景代碼:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
namespace inputfile
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
protected void Button1_Click(object sender, EventArgs e)
{//擷取檔案資訊
string FileName = File1.PostedFile.FileName;
string file_str = "檔案名稱:" + FileName + "<br>";
file_str="檔案類型:"+File1.PostedFile.ContentType+"<br>";
file_str="檔案長度:"+File1.PostedFile.ContentLength.ToString()+"KB<br>";
//上傳檔案到伺服器
FileName = FileName.Substring(FileName.LastIndexOf("\\") + 1);//取出檔案名的路徑(不包括檔案的名稱)
string upload_file = Server.MapPath("./upload/") + FileName;//取出伺服器虛拟路徑,存儲上傳檔案
File1.PostedFile.SaveAs(upload_file);//開始上傳檔案
Label1.Text =file_str+ "上傳檔案成功";
}
}
常用屬性:
(1)FileUpload1.HasFile用來檢查 FileUpload是否有指定檔案。
(2)HttpContext.Current.Request.MapPath("~/") 則是擷取網站所在的磁盤絕對路徑的,如D:\Inetpub\ServerControls\路徑,之是以要這麼做,是因為FileUpload控件必須 指定“絕對路徑”,而非相對路徑,同時絕對路徑也必須有寫入權限。
(3)FileUpload1.SaveAs()則是将上傳檔案 存儲在磁盤的方法。
(4)FileUpload1.FileName用于擷取上傳檔案名稱。
(5)FileUpload1.PostedFile.ContentLength 用于設定或擷取上傳檔案大小,以Byte為機關。
(6)FileUpload1.PostedFile.ContentType 用于設定或擷取上傳檔案的類型
執行個體效果圖:
<a href="http://www.cnblogs.com/shenzhoulong"></a>
上傳完成:
本文轉自shenzhoulong 51CTO部落格,原文連結:http://blog.51cto.com/shenzhoulong/303131,如需轉載請自行聯系原作者