使用 Visual C# 将文件上传到网站
本文介绍如何使用 Microsoft Visual C# 上传文件。
原始产品版本: Visual C#、ASP.NET、Internet Information Services
原始 KB 编号: 816150
简介
本分步文章讨论如何将现有映像文件从本地硬盘驱动器上传到网站。 输入控件用于从本地计算机上传图像。 正在上传的此文件针对服务器进行验证,以确保不会覆盖已上传的现有文件。 如果上传的文件存在于服务器上,则会对其进行验证。 本文使用 EncType
窗体的 属性来实现功能。
要求
本文假定你熟悉以下主题:
- Web 应用程序
- ASP.NET
以下列表概述了所需的建议软件和网络基础结构:
- Visual C# .NET 或 Visual C#
- Internet 信息服务 (IIS)
创建 ASP.NET Web 窗体
启动 Visual Studio .NET 或 Visual Studio。
在"文件"菜单上,指向"新建",然后单击"项目"。
注意
在 Visual Studio 中,指向“文件”菜单上的“新建”,然后单击“网站”。
在“ 项目类型”下,单击“ Visual C# 项目”。 在 “模板”下,单击“ ASP.NET Web 应用程序”。
注意
在 Visual Studio 中,选择“语言”右侧的“Visual C#”。 在 “模板”下,单击“ ASP.NET 网站”。
在“ 位置 ”框中,键入以下位置,然后单击“ 确定”:
http://WebServerName/ApplicationName
注意
WebServerName 是 Web 服务器名称的占位符。 ApplicationName 是应用程序名称的占位符。
默认情况下, 会创建WebForm1.aspx 。
注意
在 Visual Studio 中,选择“位置”右侧的“HTTP”,然后键入
<http://WebServerName>
。在“ 视图 ”菜单上,单击“ HTML 源”。
注意
在 Visual Studio 中,单击“视图”菜单上的“代码”。
修改窗体属性
在 WebForm1 的 HTML 窗口中,将表单标记替换为以下内容:
<form id="Form1" method="post" runat="server" EncType="multipart/form-data" action="WebForm1.aspx">
属性 EncType
指定发布的数据的格式。 浏览器使用此属性对发布到服务器的信息进行编码。 此代码中的操作属性指定页面将处理请求。 默认情况下,窗体的方法属性设置为 post,以便可以在事务中发送大量数据。
添加输入控件以指定要上传到服务器的文件
在 WebForm1 的 HTML 窗口中,在开始标记和结束
<form>
标记之间添加以下代码:<INPUT id="oFile" type="file" runat="server" NAME="oFile">
此输入控件指定要上传到服务器的文件。
可以在控件前面添加文本字符串以提示用户。 在 WebForm1 的 HTML 窗口中的 Input 控件前面键入以下文本:
选择要上传到服务器的图像文件:
添加按钮控件
在 WebForm1 的 HTML 窗口中,在输入控件代码之后的开始标记和结束
<form>
标记之间添加以下代码:<asp:button id="btnUpload" type="submit" text="Upload" runat="server"></asp:button>
此按钮控件用于上传在输入控件中指定的文件。
创建包含单个标签的面板控件以显示输出
在 WebForm1 的 HTML 窗口中,在“按钮”控件代码之后的开始标记和结束<form>
标记之间添加以下代码:
<asp:Panel ID="frmConfirmation" Visible="False" Runat="server">
<asp:Label id="lblUploadResult" Runat="server"></asp:Label>
</asp:Panel>
此代码用于显示消息,以指示文件上传是否成功。 若要显示此输出,将创建包含单个标签的面板控件。
在“按钮单击”事件上上传文件
本部分中的代码从本地文件系统中检索文件,检查该文件是否已存在于服务器上,然后将文件上传到网站。 若要添加此代码,请执行以下步骤:
双击在本文的“添加按钮控件”部分中创建的“上传”按钮,为
Click
按钮控件的事件创建事件处理程序。在“ 代码” 窗口顶部添加以下代码:
using System.IO;
将以下代码添加到
Click
“上传”按钮的事件处理程序:string strFileName; string strFilePath; string strFolder; strFolder = Server.MapPath("./"); // Retrieve the name of the file that is posted. strFileName = oFile.PostedFile.FileName; strFileName = Path.GetFileName(strFileName); if(oFile.Value != "") { // Create the folder if it does not exist. if(!Directory.Exists(strFolder)) { Directory.CreateDirectory(strFolder); } // Save the uploaded file to the server. strFilePath = strFolder + strFileName; if(File.Exists(strFilePath)) { lblUploadResult.Text = strFileName + " already exists on the server!"; } else { oFile.PostedFile.SaveAs(strFilePath); lblUploadResult.Text = strFileName + " has been successfully uploaded."; } } else { lblUploadResult.Text = "Click 'Browse' to select the file to upload."; } // Display the result of the upload. frmConfirmation.Visible = true;
在“文件”菜单上单击“全部保存”。
验证上传操作是否有效
在 “调试 ”菜单上,单击“ 开始 ”以生成并运行应用程序。 将显示一个文本框和一个命令按钮。
在文本框中键入图像文件的路径,或单击“ 浏览 ”在本地计算机上找到图像文件。
单击“ 上传 ”将文件发送到服务器。 如果文件是唯一的,则会收到一条消息,指出上传成功。 如果服务器上已存在该文件,则会收到相应的消息。 从此应用程序上传的文件保存在本地硬盘上的位置
C:\inetpub\wwwroot\ApplicationName
。若要使此应用程序在.NET Framework中正常工作,请允许对 ASPNET 用户进行完全控制访问。 为此,请按照下列步骤操作:
在 Windows 资源管理器中找到应用程序文件夹。 路径为
C:\inetpub\wwwroot\ApplicationName
。右键单击 ApplicationName 文件夹,然后单击 “属性”。 此时会显示“ ApplicationName 属性 ”对话框。
单击“安全”选项卡。
单击“添加”。 此时将显示 “选择用户或组 ”对话框。
注意
在 Visual Studio 中,将显示 “选择用户、计算机或组 ”对话框。
在“输入要选择的对象名称”框中键入 ASPNET,然后单击“确定”。
在“ApplicationName 属性”对话框中,单击“组或用户名”列表中的 ASPNET 用户。
在“允许”下,单击以选中“完全控制检查”框,然后单击“确定”。
完整代码列表
WebForm1.aspx
<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="Howto.WebForm1" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <HTML> <HEAD> <title>WebForm1</title> <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" Content="C#"> <meta name="vs_defaultClientScript" content="JavaScript"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5"> </HEAD> <body MS_POSITIONING="GridLayout"> <form id="Form1" method="post" runat="server" EncType="multipart/form-data" action="WebForm1.aspx"> Image file to upload to the server: <INPUT id="oFile" type="file" runat="server" NAME="oFile"> <asp:button id="btnUpload" type="submit" text="Upload" runat="server"></asp:button> <asp:Panel ID="frmConfirmation" Visible="False" Runat="server"> <asp:Label id="lblUploadResult" Runat="server"></asp:Label> </asp:Panel> </form> </body> </HTML>
WebForm1.aspx.cs
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.IO; namespace **ApplicationName** { /// <summary> /// Summary description for WebForm1. /// </summary> public class WebForm1 : System.Web.UI.Page { protected System.Web.UI.WebControls.Button btnUpload; protected System.Web.UI.WebControls.Label lblUploadResult; protected System.Web.UI.WebControls.Panel frmConfirmation; protected System.Web.UI.HtmlControls.HtmlInputFile oFile; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // CODEGEN: This call is required by the ASP.NET Web Form Designer. InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.btnUpload.Click += new System.EventHandler(this.btnUpload_Click); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void btnUpload_Click(object sender, System.EventArgs e) { string strFileName; string strFilePath; string strFolder; strFolder = Server.MapPath("./"); // Get the name of the file that is posted. strFileName = oFile.PostedFile.FileName; strFileName = Path.GetFileName(strFileName); if(oFile.Value != "") { // Create the directory if it does not exist. if(!Directory.Exists(strFolder)) { Directory.CreateDirectory(strFolder); } // Save the uploaded file to the server. strFilePath = strFolder + strFileName; if(File.Exists(strFilePath)) { lblUploadResult.Text = strFileName + " already exists on the server!"; } else { oFile.PostedFile.SaveAs(strFilePath); lblUploadResult.Text = strFileName + " has been successfully uploaded."; } } else { lblUploadResult.Text = "Click 'Browse' to select the file to upload."; } // Display the result of the upload. frmConfirmation.Visible = true; } }
注意
Visual Studio 中生成的代码与 Visual Studio .NET 中生成的代码不同。
疑难解答
- 打开计算机上的 Machine.config 文件,该文件位于安装运行时的路径下的 CONFIG 文件夹中。
<processModel>
在 Machine.config 文件中查找 部分,将 和password
属性更改为user
要 W3wp.exe 或 Aspnet_wp.exe 运行的用户的名称和密码,然后保存 Machine.config 文件。- 找到 CONFIG 文件夹中的“临时 ASP.NET 文件”文件夹。 右键单击“ 临时 ASP.NET 文件” 文件夹,然后单击“ 属性”。
- 在 “临时 ASP.NET 文件属性 ”对话框中,单击“ 安全性 ”选项卡。
- 单击“高级”。
- 在“临时 ASP.NET 文件的访问控制设置”对话框中,单击“添加”。
- 在对话框中的“ 名称 ”框中键入用户名,然后单击“ 确定”。
- 在“ 临时 ASP.NET 文件的权限条目 ”对话框中,向用户授予完全权限,然后单击“ 确定 ”关闭 “临时 ASP.NET 文件属性 ”对话框。
References
反馈
https://aka.ms/ContentUserFeedback。
即将发布:在整个 2024 年,我们将逐步淘汰作为内容反馈机制的“GitHub 问题”,并将其取代为新的反馈系统。 有关详细信息,请参阅:提交和查看相关反馈