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

Web design and development based in Royston, Hertfordshire, United Kingdom

Griffiths Web Design

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

07709 579517

michael@griffithswebdesign.com

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

By Michael Griffiths

Created: 16.06.2016 00:00:00, last updated: 01.01.1900 00:00:00

Uploading files with ASP.NET’s asp:fileupload control in 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:


<asp:fileupload id="FileUpload1" runat="server">
<asp:button id="btnUpload" onclick="" runat="server" text="Upload">

We also need a repeater control. Your repeater should look like this:


<asp:repeater id="rptImgs" runat="server">
<itemtemplate>
<div class="col-sm-3">
<asp:image id="img1" runat="server" imageurl="">
</asp:image></div>
</itemtemplate>
</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 those soon to fill them in.

For the purposes of displaying error messages I also created an empty label control, like so:


<asp:label id="lblError" runat="server"></asp:label>

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:


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;
}

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.


if (!this.IsPostBack)
{
rptImgs.DataSource = GetImageNames();
rptImgs.DataBind();
}

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:


<asp:image id="img1" runat="server" imageurl='<%#"imageUploads/" + Eval("Name") %>'>

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:


<asp:button id="btnUpload" onclick="btnUpload_Click" runat="server" text="Upload">

In your code behind file you need to add the following using statement:

using System.IO;

Then add this line into your page class:


private string upDir;

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’


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.


// 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;
}
}

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:


FileUpload1.PostedFile.SaveAs(fPath);

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.

Something to be aware of:

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:


<configuration>
<system.web>
<httpruntime maxrequestlength="1048576">
</httpruntime></system.web>
</configuration>

For IIS7 and above, you also need to add:


<system.webserver>
<security>
<requestfiltering>
<requestlimits maxallowedcontentlength="1073741824">
</requestlimits></requestfiltering>
</security>
</system.webserver>

Note: 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. 




</asp:button></asp:image></fileinfo></fileinfo></fileinfo></asp:button></asp:fileupload>

About Michael Griffiths

Web Developer and Social Media Coach

Comments

Comment posted by: Bogdanleb

13.12.2019 07:00:58

Приветствую Вас друзья<a href=https://stekloelit.by>!</a> Предлагаем Вашему вниманию изделия из стекла для дома и офиса.Наша организация ООО «СТЕКЛОЭЛИТ» работает 10 лет на рынке этой продукции в Беларуси. Мы можем предложить Вам <a href=https://stekloelit.by>Межкомнатные стеклянные двери</a>,<a href=https://stekloelit.by>Офисные стеклянные перегородки</a>,<a href=https://stekloelit.by>Душевые кабины из закаленного стекла</a>,<a href=https://stekloelit.by>Стеклянные двери в душ</a> и <a href=https://stekloelit.by>Лестничное ограждение из стекла</a>,а также<a href=https://stekloelit.by>Стеклянные козырьки</a> и <a href=https://stekloelit.by>Интерьерные перегородки</a> Более подробная информация размещена на нашем <a href=https://stekloelit.by>сайте</a> http://99.tqcp.net/home.php?mod=space&uid=408480 http://mastersamodelka.ru/index/8-54369 https://forum.mobilism.org/memberlist.php?mode=viewprofile&u=1187284 http://www.cfmgei.ru/index/8-56331 http://www.crazys.cc/forum/space-uid-384907.html

Comment posted by: Helenalei

12.12.2019 07:30:41

Здравствуйте товарищи<a href=https://mfc-ritual.by/>!</a> Наша организация занимается свыше 10 лет ритуальными услугами в городе Минске.Вот что мы можем предложить вам: 1)<a href=https://mfc-ritual.by/>ритуальные услуги</a> –Мы более десяти лет предоставляем услуги ритуального характера в Минске и Минской области, помогаем достойно проводить усопшего в последний путь. 2)<a href=https://mfc-ritual.by/>ритуальные услуги минск</a>-Мы оказываем ритуальные услуги с набором всего необходимого товара и сервиса, которые предлагаем, опираясь на возможные финансовые затраты клиента. 3)<a href=https://mfc-ritual.by/>организация похорон</a>-Сотрудники нашего ритуального агентства – это специалисты высокого класса с большим опытом работы. 4)<a href=https://mfc-ritual.by/>организация похорон минск</a>-Наш многофункциональный похоронно-ритуальный центр обеспечит качественные похороны с полным набором требуемых ритуальных услуг. http://the-cinema.be/user/Helenaacq/ http://ar.doctormoslemi.ir/user/Patriotbdh/ http://begi-za-mnoy.ru/user/Patriotvzu/ http://poster.berdyansk.net/user/Patriotsjo/ http://www.a-drozdov.ru/talk/profile.php?id=58359