📜  ASP.Net Fileuplaod

📅  最后修改于: 2020-12-27 13:34:31             🧑  作者: Mango

ASP.NET Web窗体FileUpload

它是一个输入控制器,用于将文件上传到服务器。它在窗体上创建一个浏览按钮,该按钮弹出一个窗口以从本地计算机中选择文件。

要实现FileUpload,我们可以将其从Visual Studio的工具箱中拖动。

这是一个服务器端控件,ASP.NET提供了自己的标签来创建它。下面给出示例。

< asp:FileUpload ID="FileUpload1" runat="server"/>

服务器将其呈现为HTML控件,并向浏览器生成以下代码。


该控件具有自己的属性,如下表所示。

Property Description
AccessKey It is used to set keyboard shortcut for the control.
TabIndex The tab order of the control.
BackColor It is used to set background color of the control.
BorderColor It is used to set border color of the control.
BorderWidth It is used to set width of border of the control.
Font It is used to set font for the control text.
ForeColor It is used to set color of the control text.
Text It is used to set text to be shown for the control.
ToolTip It displays the text when mouse is over the control.
Visible To set visibility of control on the form.
Height It is used to set height of the control.
Width It is used to set width of the control.
AllowMultiple It is used to allow upload multiple files by setting true or false.

FileUpload属性窗口

在这里,我们正在以Web形式实现文件上传控制。

// WebControls.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebControls.aspx.cs" 
Inherits="WebFormsControlls.WebControls" %>



    


    

Browse to Upload File

// WebControls.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebFormsControlls
{
    public partial class WebControls : System.Web.UI.Page
    {
        protected System.Web.UI.HtmlControls.HtmlInputFile File1;
        protected System.Web.UI.HtmlControls.HtmlInputButton Submit1;
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            if ((FileUpload1.PostedFile != null) && (FileUpload1.PostedFile.ContentLength > 0))
            {
                string fn = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
                string SaveLocation = Server.MapPath("upload") + "\\" + fn;
                try
                {
                    FileUpload1.PostedFile.SaveAs(SaveLocation);
                    FileUploadStatus.Text = "The file has been uploaded.";
                }
                catch (Exception ex)
                {
                    FileUploadStatus.Text = "Error: " + ex.Message;
                }
            }
            else
            {
                FileUploadStatus.Text = "Please select a file to upload.";
            }
        }
    }
}

像在下面的屏幕快照中一样,在项目中创建一个目录来存储上载的文件。

输出:

输出:

运行代码,它将产生以下输出。

我们正在上传文件c#programs.txt。

上载后,它将显示成功上传文件的消息,如以下屏幕截图所示。

该文件存储在上载文件夹中。在文件夹中查看,它显示了已上传的文件。