Uploading Files With ASP.NET's FileUpload Control In C#

We’ve seen and almost certainly used the websites that allow the users to upload the files to the Server. Now, we will discover how they do it. We will be using ASP.NET’s file upload control, though there are plenty of other options but you will be hard pressed to find one that is easier to use and implement.

At this point, I want to state that allowing the users to upload the files can be dangerous if misused. Therefore, be careful how you use it. In our example, we will only be allowing the upload of the image files, specifically PNG’s and JPEG’s.

In this article, we will allow the users to upload the files to the Server by using the ASP:fileupload control. We will also validate the file extension and only allow the previously mentioned file types. We will also use an ASP:repeater to display the uploaded images, so the user can see that it has worked.

First, open Visual Studio and create an empty ASP.NET website.

Note

Even if you want to implement this into an existing Application, I would still recommend creating a new empty site to play around with. 

In the website we just created, we need to add a new folder and I’m calling mine imageUploads. This folder is where we will store the uploaded images.

Next, we need to create a new Webform. As this is the only page in our site, mine is called ‘Default.aspx’. This is where the fun begins.

On our Webform, we need an ASP:fileUploadControl and an ASP:button. The file upload control comes with the button to browse the file system, but doesn’t come with the button to fire the event to validate and save the file. In order to solve this, the extra button is provided. Your mark-up for the two controls should look like:

  1. <asp:FileUpload ID="FileUpload1" runat="server" />  
  2. <asp:Button ID="btnUpload" runat="server"OnClick="" Text="Upload" />  
We also need a repeater control. Your repeater should look like:
  1. <asp:Repeater ID="rptImgs" runat="server">  
  2.     <ItemTemplate>  
  3.         <div class="col-sm-3">  
  4.             <asp:Image ID="img1" ImageUrl='' runat="server" />  
  5.         </div>  
  6.     </ItemTemplate>  
  7. </asp:Repeater>  
Note

As you can see, I have left the OnClick of the button blank and the ImageUrl of the image control is also blank. Don’t worry, we will come back to these soon to fill them.

For the purposes of displaying error messages, I also created an empty label control, shown below:
  1. <asp:Label ID="lblError" runat="server"></asp:Label>  
This is the mark-up which is required. Now, we need to think about the mechanics of it. What do we need to do to achieve our goal? We need some way of getting the URL’s of the images into the repeater. We also need to validate and save the files. I started with the repeater first.

.NET has a wonderful class by the name of FileInfo which saved us from most of the hard work. We will create a list of fileInfo objects..

The code for this should loo like:
  1. public List < FileInfo > GetImageNames()  
  2. {  
  3.     string imgPath = Server.MapPath("~/imageUploads/");  
  4.     List < FileInfo > images = new List < FileInfo > ();  
  5.     DirectoryInfo directoryInfo = new DirectoryInfo(imgPath);  
  6.     FileInfo[] fileInfo = directoryInfo.GetFiles();  
  7.     foreach(FileInfo file in fileInfo)  
  8.     {  
  9.         images.Add(file);  
  10.     }  
  11.     return images;  
  12. }  
As you can see, it’s nothing complex. First, we created a string to hold the path to the folder. Next, we created an empty list called images, which will store the objects of type FileInfo. Afterwards, we initialized a new instance of DirectoryInfo and used the GetFiles() method , which returns a file list from the specified directory. It was a simple case of using a for each loop. It was used to loop through the files in this list and add them to our empty list we created. This creates the list, but it does not bind it to the repeater. Therefore to do this, we will need to add some code to the Page_Load event.
  1. if (!this.IsPostBack)  
  2. {  
  3.    rptImgs.DataSource = GetImageNames();  
  4.    rptImgs.DataBind();  
  5. }  
First, it checks to see if this is a post back and if it is not, it then assigns ‘getImageNames()’, as the data source for the repeater. The last line calls the repeaters data bind method.

We also need to add something to the mark-up, specifically the image URL. The image control in the item template of the repeater should look as follows:
  1. <asp:Image ID="img1" ImageUrl='<%#"imageUploads/" + Eval("Name") %>' runat="server"/>  
Test it out by dropping some image files into the folder ‘imageUploads’ and run the page. You’ll see the images displayed in the repeater.

Now, we can lay our emphasis on uploading the files.

First, go to your upload button in the mark-up. Add an OnClick event and hopefully it should look, as shown below:
  1. <asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click" Text="Upload" />  
In your backend file, you need to add the following using statement:
  1. using System.IO;  
Subsequently, add this line into your page class:
  1. private string upDir;  
In your Page_Load event, you need to add a value, which in this case is the physical Application path of the folder ‘imageUploads:
  1. upDir = Path.Combine(Request.PhysicalApplicationPath, "imageUploads");  
Now, locate your upload buttons click event. In that event, add the code that follows. I will explain it all at the end.
  1. // check if a file is being submitted  
  2. if (FileUpload1.PostedFile.FileName != "")  
  3. {  
  4.     // check extension  
  5.     string ext = Path.GetExtension(FileUpload1.PostedFile.FileName);  
  6.     switch (ext.ToLower())  
  7.     {  
  8.         case ".png":  
  9.         case ".jpg":  
  10.         case ".jpeg":  
  11.             break;  
  12.         default:  
  13.             lblError.Text = "Unfortunately the selected file type is not currently supported, sorry...";  
  14.             return;  
  15.     }  
  16.     // using the following 2 lines of code the file will retain its original name.  
  17.     string sfn = Path.GetFileName(FileUpload1.PostedFile.FileName);  
  18.     string fPath = Path.Combine(upDir, sfn);  
  19.     try  
  20.     {  
  21.         FileUpload1.PostedFile.SaveAs(fPath);  
  22.         rptImgs.DataSource = GetImageNames();  
  23.         rptImgs.DataBind();  
  24.     }  
  25.     catch (IOException ex)  
  26.     {  
  27.         lblError.Text = "Error uploading file: " + ex.Message;  
  28.     }  
  29.     catch (Exception er)  
  30.     {  
  31.         lblError.Text += "Unknown error: " + er.Message;  
  32.     }  
  33. }  
First, this code makes sure that there is a file selected. Next, we created a string to hold the file extension followed by making sure it is an allowed file type by use of a switch statement. Afterwards, it passes that check and we get the file name. Add it to the path set by our ‘upDir’ string. Within the Try block, we have the following line:

 

  1. FileUpload1.PostedFile.SaveAs(fPath);  
This is what saves our file to the Server.(For a call to the SaveAs to work, ASP.NET Application must have a write access to the directory on the Server). We have also re-bound the repeater to show the new images.

If you are using IIS to host your Application, the default upload file size is 4MB. To increase it, please add the following section to your web.config file:
  1. <configuration>  
  2.     <system.web>  
  3.         <httpRuntime maxRequestLength="1048576" />  
  4.     </system.web>  
  5. </configuration>  
For IIS7 and above, you also need to add:
  1. <system.webServer>  
  2.     <security>  
  3.         <requestFiltering>  
  4.             <requestLimits maxAllowedContentLength="1073741824" />  
  5.         </requestFiltering>  
  6.     </security>  
  7. </system.webServer>  
Note

maxAllowedContentLength is measured in the bytes while maxRequestLength is measured in the kilobytes, viz-a-viz the values differ in this example. (Both are equivalent to 1 GB, but allowing uploads of this size is not advisable because the Server can override your setting to prevent such large uploads.).

I hope this helps you in your future endeavors. If you have any comments or questions, please don’t hesitate to get in touch. 

Up Next
    Ebook Download
    View all
    Learn
    View all