Griffiths web design based in Royston, Hertfordshire, United Kingdom

 

Uploading files with ASP.NET’s asp:fileupload control in c#

Author:   Michael Griffiths

Date created:   16 June 2016

[c]We’ve all seen, and almost certainly used, websites that allow users to upload files to the server. And now we will discover how they do it. We will be using ASP.NET’s file upload control, 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 users to upload files can be dangerous if misused, so be careful how you use it. In our example we will only be allowing the upload of image files, specifically png’s and jpeg’s. In this article we will allow users to upload 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 in then once you have it down you can then implement it into your existing application with little to no issues. In the website we just created we need to add a new folder, 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, hence the extra button. Your mark-up for the two controls should look like this: [/c] [code] [/code] [c]We also need a repeater control. Your repeater should look like this: [/c] [code]
[/code] [c][i]Note –[/i] 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 those soon to fill them in. For the purposes of displaying error messages I also created an empty label control, like so: [/c] [code][/code] [c]That is all the mark-up that is required, which as you can see is not very much at all. Now we need to think about the mechanics of it all. 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 and we also need to validate and save files. I started with the repeater first. .Net has a wonderful class by the name of FileInfo which save us from most of the hard work. We will create a List of fileInfo objects. The code for this should look like the following: [/c] [code]public List GetImageNames() { string imgPath = Server.MapPath("~/imageUploads/"); List images = new List(); DirectoryInfo directoryInfo = new DirectoryInfo(imgPath); FileInfo[] fileInfo = directoryInfo.GetFiles(); foreach (FileInfo file in fileInfo) { images.Add(file); } return images; }[/code] [c]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 objects of type FileInfo. Then we initialised a new instance of DirectoryInfo and used the GetFiles() method which returns a file list from the specified directory. Then it was a simple case of using a foreach loop 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, so to do that we will need to add some code to the Page_Load event.[/c] [code]if (!this.IsPostBack) { rptImgs.DataSource = GetImageNames(); rptImgs.DataBind(); }[/code] [c]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: [/c] [code][/code] [c]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 get down to what you came for in the first place, uploading files. First go to your upload button in the mark-up. Add an OnClick event and hopefully it should look like:[/c] [code][/code] [c]In your code behind file you need to add the following using statement:[/c][code]using System.IO;[/code] [c]Then add this line into your page class:[/c] [code]private string upDir;[/code] [c]Then in your Page_Load event you need to add a value, which in this case is the physical application path of the folder ‘imageUploads’[/c] [code]upDir = Path.Combine(Request.PhysicalApplicationPath, "imageUploads");[/code] [c]Now locate your upload buttons click event. In that event add the code that follows. I will explain it all at the end.[/c] [code]// 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; } }[/code] [c]First this code makes sure there is a file selected. Next we created a string to hold the file extension, then we make sure it is an allowed file type by use of a switch statement. After it passes that check we get the file name and add it to the path set by our ‘upDir’ string. Within the try block we have the following line:[/c] [code]FileUpload1.PostedFile.SaveAs(fPath);[/code] [c]This is what saves our file to the server. (For a call to the SaveAs to work, the ASP.NET application must have write access to the directory on the server). We have also re-bound the repeater to show the new images. [b]Something to be aware of:[/b] If you are using IIS to hostyour application, then the default upload file size is 4MB. To increase it, please add the following section to your web.config file:[/c] [code] [/code] [c]For IIS7 and above, you also need to add: [/c] [code] [/code] [c][b]Note: [/b]maxAllowedContentLength is measured in bytes while maxRequestLength is measured in kilobytes, which is why the values differ in this example. (Both are equivalent to 1 GB.) And there you have it. I hope this helps you in your future endeavours. If you have any comments or questions please don’t hesitate to get in touch.  [/c]

About the author

My name is Michael Griffiths, I am a website designer and developer and the owner of Griffiths Web Design. I am based in Royston, Hertfordshire. Most of my work is local, Hertfordshire, Cambridgeshire, Bedfordshire, Essex etc. but that’s not to say I won’t work elsewhere. One of the wonders of modern technology is remote working. So no matter where the client is located it is always possible to connect.

I specialise in creating ASP.NET webforms applications using C#. I use Microsoft SQL Server for database development and on the front end I use Html, CSS and JavaScript. I am also proficient in the use of jQuery and several CSS frameworks.

One of my greatest passions in life is learning. Which is why I chose to pursue a career in web design and development, technology is in a state of constant and rapid evolution which means there is always something new to learn. I also enjoy writing, both fiction and non-fiction.

Comments

Please feel free to leave a comment below:






 
Griffiths Web Design Logo by Michael Griffiths
Griffiths Web Design Logo by Michael Griffiths
Click to go to the top of the page