如何正确使用 ASP.NET FileUpload 控件 [英] How to correctly use the ASP.NET FileUpload control

查看:28
本文介绍了如何正确使用 ASP.NET FileUpload 控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 ASP.NET 中使用 FileUpload 控件

I'm trying to use the FileUpload control in ASP.NET

这是我当前的命名空间设置:

Here's my current namespace setup:

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

在我的课堂上,我只是使用:

And within my class, I'm just using:

FileUpload fileUpload = new FileUpload();

但是,通常属于 FileUpload 一部分的属性似乎都不可用……例如 .HasFile.我试图在后面的代码中创建 Button click 方法,我注意到 .HasFile 的大部分用法都在前面的代码中,但我的理解是这应该无关紧要.

However, none of the attributes that are normally part of FileUpload seem to be available... such as .HasFile. I'm attempting to make the Button click method in the code behind, I have noticed that most of the usage of .HasFile is in the code in front, however it was my understanding that this shouldn't matter.

有人知道为什么吗?

推荐答案

ASP.NET 控件应该放在 aspx 标记文件中.这是与他们合作的首选方式.因此,将 FileUpload 控件添加到您的页面.确保它具有所有必需的属性,包括 IDrunat:

ASP.NET controls should rather be placed in aspx markup file. That is the preferred way of working with them. So add FileUpload control to your page. Make sure it has all required attributes including ID and runat:

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

FileUpload1 的实例将在自动生成/更新的 *.designer.cs 文件中自动创建,该文件是您页面的部分类.您通常不必关心其中的内容,只需假设 aspx 页面上的任何控件都会自动实例化.

Instance of FileUpload1 will be automatically created in auto-generated/updated *.designer.cs file which is a partial class for your page. You usually do not have to care about what's in it, just assume that any control on an aspx page is automatically instantiated.

添加一个按钮来回发:

<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />

然后转到您拥有代码的 *.aspx.cs 文件并添加按钮单击处理程序.在 C# 中,它看起来像这样:

Then go to your *.aspx.cs file where you have your code and add button click handler. In C# it looks like this:

protected void Button1_Click(object sender, EventArgs e)
{
  if (this.FileUpload1.HasFile)
  {
    this.FileUpload1.SaveAs("c:\" + this.FileUpload1.FileName);
  }
}

就是这样.一切都应该按预期工作.

And that's it. All should work as expected.

这篇关于如何正确使用 ASP.NET FileUpload 控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆