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:
- <asp:FileUpload ID="FileUpload1" runat="server" />
- <asp:Button ID="btnUpload" runat="server"OnClick="" Text="Upload" />
- <asp:Repeater ID="rptImgs" runat="server">
- <ItemTemplate>
- <div class="col-sm-3">
- <asp:Image ID="img1" ImageUrl='' runat="server" />
- </div>
- </ItemTemplate>
- </asp:Repeater>
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:
- <asp:Label ID="lblError" runat="server"></asp:Label>
.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:
- public List < FileInfo > GetImageNames()
- {
- string imgPath = Server.MapPath("~/imageUploads/");
- List < FileInfo > images = new List < FileInfo > ();
- DirectoryInfo directoryInfo = new DirectoryInfo(imgPath);
- FileInfo[] fileInfo = directoryInfo.GetFiles();
- foreach(FileInfo file in fileInfo)
- {
- images.Add(file);
- }
- return images;
- }
- if (!this.IsPostBack)
- {
- rptImgs.DataSource = GetImageNames();
- rptImgs.DataBind();
- }
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:
- <asp:Image ID="img1" ImageUrl='<%#"imageUploads/" + Eval("Name") %>' runat="server"/>
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:
- <asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click" Text="Upload" />
- using System.IO;
- private string upDir;
- upDir = Path.Combine(Request.PhysicalApplicationPath, "imageUploads");
- // check if a file is being submitted
- if (FileUpload1.PostedFile.FileName != "")
- {
- // check extension
- string ext = Path.GetExtension(FileUpload1.PostedFile.FileName);
- switch (ext.ToLower())
- {
- case ".png":
- case ".jpg":
- case ".jpeg":
- break;
- default:
- lblError.Text = "Unfortunately the selected file type is not currently supported, sorry...";
- return;
- }
- // using the following 2 lines of code the file will retain its original name.
- string sfn = Path.GetFileName(FileUpload1.PostedFile.FileName);
- string fPath = Path.Combine(upDir, sfn);
- try
- {
- FileUpload1.PostedFile.SaveAs(fPath);
- rptImgs.DataSource = GetImageNames();
- rptImgs.DataBind();
- }
- catch (IOException ex)
- {
- lblError.Text = "Error uploading file: " + ex.Message;
- }
- catch (Exception er)
- {
- lblError.Text += "Unknown error: " + er.Message;
- }
- }
- FileUpload1.PostedFile.SaveAs(fPath);
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:
- <configuration>
- <system.web>
- <httpRuntime maxRequestLength="1048576" />
- </system.web>
- </configuration>
- <system.webServer>
- <security>
- <requestFiltering>
- <requestLimits maxAllowedContentLength="1073741824" />
- </requestFiltering>
- </security>
- </system.webServer>
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.

javier cacaoPosted Apr 13, 2022, 2:16 PM
// check if a file is being submitted if (FileUpload1.PostedFile.FileName != "") <- what about FileUpload1.HasFile ? {
Nikhil SanganiPosted Jun 24, 2016, 8:33 AM
Nice
Kuppurasu NagarajPosted Jun 21, 2016, 12:41 PM
Nice Sharing..
Debasis SahaPosted Jun 21, 2016, 12:48 AM
Good One..
Michael GriffithsPosted Jun 20, 2016, 2:09 PM
Thank you
kalu singh raoPosted Jun 20, 2016, 1:58 PM
Nice...