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();
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.
Does anyone know why?
The two controls used to upload files to a web server are: HtmlInputFile - an HTML server control. File Upload - an ASP.NET server control.
As we know session object can store any object and in case of OutProc/State Server Serializable Object only. So idea is very simple store fileupload object in session and in the post back get the values back from it. Use this code in Page_Load.
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" />
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.
Add a button that will do the post back:
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With