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

在C# ASP.NET Web中,使用FileUpload控件可以实现上传文件,即把客户机的某个文件上传到服务器的某个目录下。在此我只写一个简单的实例供参考。

FileUpload.aspx文件如下:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="UseFileUpload.aspx.cs" Inherits="UseFileUpload" %>





    使用FileUpload控件上传文件


    

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 += "
"; this.Label1.Text += "
  • " + "原文件路径:" + this.FileUpload1.PostedFile.FileName; this.Label1.Text += "
    "; this.Label1.Text += "
  • " + "文件大小:" + this.FileUpload1.PostedFile.ContentLength + "字节"; this.Label1.Text += "
    "; this.Label1.Text += "
  • " + "文件类型:" + this.FileUpload1.PostedFile.ContentType; this.Label1.Text += "
    "; this.Label1.Text += "
  • " + "服务器路径:" + this.Server.MapPath("~/CopyFile/") +FileUpload1.FileName; } catch { this.Label1.Text = "文件上传不成功!"; } finally { } } } }
  •   觉得对你有帮助的麻烦点个赞再走!

    你可能感兴趣的:(C#)