在C# ASP.NET Web中,使用FileUpload控件可以實現上傳文件,即把客戶機的某個文件上傳到服務器的某個目錄下。在此我只寫一個簡單的實例供參考。
FileUpload.aspx文件如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="UseFileUpload.aspx.cs" Inherits="UseFileUpload" %>
<!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 id="Head1" runat="server">
<title>使用FileUpload控件上傳文件</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="FileUpload1" runat="server" Width="243px" /><asp:Button ID="Button1"
runat="server" OnClick="Button1_Click" Text="上傳" />
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
FileUpload.aspx.cs文件如下
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class UseFileUpload : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
//判斷上傳文件是否爲空
if (FileUpload1.PostedFile != null)
{
//獲取上傳文件的路徑和文件名
string strDir = FileUpload1.PostedFile.FileName;
try
{
this.FileUpload1.SaveAs(Server.MapPath("~/CopyFile/") + FileUpload1.FileName); // ~/CopyFile/表示項目的根目錄
this.Label1.Text = "文件上傳成功";
this.Label1.Text += "<Br/>";
this.Label1.Text += "<li>" + "原文件路徑:" + this.FileUpload1.PostedFile.FileName;
this.Label1.Text += "<Br/>";
this.Label1.Text += "<li>" + "文件大小:" + this.FileUpload1.PostedFile.ContentLength + "字節";
this.Label1.Text += "<Br/>";
this.Label1.Text += "<li>" + "文件類型:" + this.FileUpload1.PostedFile.ContentType;
this.Label1.Text += "<Br/>";
this.Label1.Text += "<li>" + "服務器路徑:" + this.Server.MapPath("~/CopyFile/") +FileUpload1.FileName;
}
catch
{
this.Label1.Text = "文件上傳不成功!";
}
finally
{
}
}
}
}
覺得對你有幫助的麻煩點個贊再走!