欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C# Web服务器控件FileUpload()上传文件

程序员文章站 2022-05-09 11:18:25
...

在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
            {

            }
        }
   }
}

  觉得对你有帮助的麻烦点个赞再走!