How to define an UploadFile function on a BasePage so that it can be reused on many aspx pages

99 Views Asked by At

I am trying to move an UploadFile function to a BasePage so that I can re-use it on many aspx pages. My original code is as follows:

upload.aspx.cs

public partial class upload : CodeBasePage
{

protected void uploadFile_Click(object sender, EventArgs e)
{
   if (UploadImages.HasFiles)
   { 
   try
   {
     foreach (HttpPostedFile uploadedFile in UploadImages.PostedFiles)
     { 
     //Upload stuff;
     }
   ...

upload.aspx

<asp:FileUpload runat="server" ID="UploadImages" />
<asp:Button runat="server" ID="uploadedFile" Text="Upload" OnClick="uploadFile_Click"/>

So far so good. The code works fine.

Now I want to move the uploadFile_Click to the BasePage (CodeBasePage) so that I can re-use it on many aspx pages.

I moved the following to the CodeBasePage and declared the variables:

CodeBasePage.cs

public Button uploadedFile;
public FileUpload UploadImages;

protected void uploadFile_Click(object sender, EventArgs e)
{
   if (UploadImages.HasFiles)
   { 
   try
   {
     foreach (HttpPostedFile uploadedFile in UploadImages.PostedFiles)
     { 
     //Upload stuff;
     }
   ...

But apparently I'm doing something wrong. When I click the Upload button on the aspx page I get the error that "Object reference not set to an instance of an object".

Line 292:            if (UploadImages.HasFiles)

Any advice would be appreciated. I think the problem lies in how to send the upload variables from the upload.aspx page to the CodeBasePage.cs.

1

There are 1 best solutions below

3
On

So you are missing a concrete FileUpload instance in your CodeBasePage class.

What you have

public FileUpload UploadImages

is only a reference. You should set it to a concrete instance either in the constructor or later by hand.

For the upload.aspx page your concrete instance is

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