How to use asp.net file upload control

This asp.net tutorial, we will see how to use asp.net file upload control with various examples like:

  • File upload and thumbnail creation in Asp.Net
  • Upload multiple files in Asp.Net file upload control
  • Read file upload control file content in Asp.Net
  • How to implement File Upload Control in Update Panel using asp.net?

File upload and thumbnail creation in Asp.Net

Now, we will see how to upload the file to a specified path and create a thumbnail for the particular image in asp.net.

To upload an image file we will use FileUpload asp.net control which is available in Visual Studio toolbox. Also here we will check the size of the image and the extension also.

HTML Code:

<asp:FileUpload ID="FileUpload1″ runat="server" Width="300px" />
<br />
<asp:Button ID="btnUpload" runat="server" EnableViewState="true" Text="Upload" OnClick="btnUpload_Click" />
<br />
<asp:Label ID="lblStatus" runat="server" Text="" ForeColor="Red"></asp:Label>

Here in the above code, we have one upload button and one label to show any error message.

C#.Net Code:

Button Click Code

try
        {
            if (FileUpload1.PostedFile != null)
            {
                int fileSize = FileUpload1.PostedFile.ContentLength;
                if (fileSize > 524288)
                {
                    lblStatus.Text = "Please upload file with maximum size 0.5MB";
                    return;
                }
                string extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
                ArrayList arrExtensionList = new ArrayList();
                arrExtensionList.Add(".png");
                arrExtensionList.Add(".jpg");
                arrExtensionList.Add(".jpeg");
                arrExtensionList.Add(".bmp");
                arrExtensionList.Add(".gif");
                arrExtensionList.Add(".tif");
                if (!arrExtensionList.Contains(extension.ToLower()))
                {
                    lblStatus.Text = "Please upload a valid image file. (.png,.jpg,.jpeg,.bmp,.gif,.tif)";
                    return;
                }
	string ImageName = "SampleImage1.png";
                FileUpload1.SaveAs(Server.MapPath("~\\UserPhoto\\") + ImageName);
                string ThumbnailPath = (Server.MapPath("~\\UserPhoto\\MyImage.png");
                using (System.Drawing.Image Img =
                System.Drawing.Image.FromFile(Server.MapPath("~\\UserPhoto\\") + ImageName))
                {
                    Size ThumbNailSize = NewImageSize(Img.Height, Img.Width, 150);
                    using (System.Drawing.Image ImgThnail =
                        new Bitmap(Img, ThumbNailSize.Width, ThumbNailSize.Height))
                    {
                        ImgThnail.Save(ThumbnailPath, Img.RawFormat);
                        ImgThnail.Dispose();
                    }
                    Img.Dispose();
	     //The below line is to delete the original image after thumbnail creation.
                    File.Delete(Server.MapPath("~\\UserPhoto\\") + ImageName);
                }
            }
        }
        catch (Exception ex)
        {
            CommonFunctions.SendExceptionMessage(ex.StackTrace);
        }

The below function is to decide the Size of the thumbnail image.

public Size NewImageSize(int OriginalHeight, int OriginalWidth, double FormatSize)
    {
        Size NewSize;
        double tempval;
        if (OriginalHeight > FormatSize && OriginalWidth > FormatSize)
        {
            if (OriginalHeight > OriginalWidth)
                tempval = FormatSize / Convert.ToDouble(OriginalHeight);
            else
                tempval = FormatSize / Convert.ToDouble(OriginalWidth);
            NewSize = new Size(Convert.ToInt32(tempval * OriginalWidth), Convert.ToInt32(tempval * OriginalHeight));
        }
        else
            NewSize = new Size(OriginalWidth, OriginalHeight); return NewSize;
    }

This way we can upload file and create thumbnail in Asp.Net using the file upload control.

Upload multiple files in Asp.Net file upload control

Now, we will see how to upload multiple files in Asp.Net file upload control.

To upload multiple photos using File Upload control we need to add multiple=”true” attribute to the file upload control.

Even if the property did not come in visual studio intellisense, you write this property it will not give any error. (For me it did not give any error so hoping it will not give any error for you also)

Below is the full code:

HTML:

<div>
<asp:FileUpload ID="FileUpload1″ runat="server" multiple="true" Width="330px" /><br />
<asp:Button ID="btnUpload" runat="server" Text="Click to Upload" OnClick="btnUpload_Click" />
</div>

.CS code:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnUpload_Click(object sender, EventArgs e)
{
HttpFileCollection fileCollection = Request.Files;
for (int i = 0; i < fileCollection.Count; i++)
{
HttpPostedFile uploadfile = fileCollection[i];
string fileName = Path.GetFileName(uploadfile.FileName);
if (uploadfile.ContentLength > 0)
{
uploadfile.SaveAs(Server.MapPath(“~/Photos/") + fileName);
}
}
}
}

Here if you want to validate image file extensions, then you can follow this article.

Check the fig below, when you will select multiple files it usually selects like below:

Upload multiple files in Asp.Net file upload control

Once you upload the images will be shown.

Upload multiple files in Asp.Net file upload control

This is how we can upload multiple files using the file upload control in asp.net.

Read file upload control file content in Asp.Net

Now, we will see how to read content from a file in fileupload control directly without saving anywhere in the server.

Below is the full code to read fileupload control file content in Asp.Net:

.aspx code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ReadFileContent.aspx.cs" Inherits="ReadFileContent" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Read fileupload control file content in Asp.Net</title>
</head>
<body>
<form id="form1″ runat="server">
<div>
<asp:FileUpload ID="fuUploadFile" runat="server" /><br />
<asp:Button ID="btnReadContent" runat="server" Text="Read Content" OnClick="btnReadContent_Click" /><br />
<asp:Label ID="lblFileContent" runat="server" Text=""></asp:Label>
</div>
</form>
</body>
</html>

.aspx.cs code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;

public partial class ReadFileContent : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}

protected void btnReadContent_Click(object sender, EventArgs e)
{
if (fuUploadFile.HasFile)
{
if (fuUploadFile.PostedFile.ContentLength > 0)
{
string fullContent = string.Empty;
Stream objStream;
Int32 intFileLength = fuUploadFile.PostedFile.ContentLength;

// Create a byte array to hold the contents of the file.
Byte[] Input = new Byte[intFileLength];

// Initialize the stream to read the uploaded file.
objStream = fuUploadFile.FileContent;

// Read the file into the byte array.
objStream.Read(Input, 0, intFileLength);

UTF8Encoding encoding = new UTF8Encoding();
fullContent = encoding.GetString(Input);

lblFileContent.Text = fullContent;
}
}
}
}

The output will come as shown in the figure below:

Read file upload control file content in Asp.Net

This is how we can read file upload control file content in Asp.Net.

How to implement File Upload Control in Update Panel using asp.net?

Now, we will see an an example on how to upload Image/file through File Upload Control that will be inside Update Panel in asp.net.

While implementing, we need to set the Button that is uploading the image to be “PostBackTrigger” instead of “AsyncPostBackTrigger”. By setting so the upload button will cause the full post back and get and retain the image in the FileUpload control whenever clicked on.If you won’t follow the same many times you will find that FileUpload control will not work properly in the update panel.

To set the button as “PostBackTrigger”.Mention like below.

<Triggers>
<asp:PostBackTrigger ControlID="btnUpload1″ />
</Triggers>

Implementation:

  • In the (.aspx) page, place a FileUpload Control and a Button control and also place ScriptManager from the AJAX Extension category.
  • create a folder in the root directory of your project and give it name “Images”. We will store our uploaded image in this folder.
<div>
<fieldset style="width:300px;">
<legend>Upload file example</legend>
<asp:ScriptManager ID="ScriptManager1″ runat="server">
</asp:ScriptManager>
<table>
<tr>
<td>
<asp:UpdatePanel ID="UpdatePanel1″ runat="server">
<ContentTemplate>
<asp:FileUpload ID="FileUpload1″ runat="server" />
<asp:Button ID="btnUpload1″ runat="server" Text="Upload"
onclick="btnUpload1_Click" /><br />
<asp:Image ID="imgRaj" runat="server" Width="150px" />
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="btnUpload1″ />
</Triggers>
</asp:UpdatePanel>
</td>
</tr>
</table>
</fieldset>
</div>

Code Behind:

In the code behind file(.aspx.cs) write the code on the upload button’s click event as:

protected void btnUpload1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string ImgPath = Server.MapPath("~/Images/" + Guid.NewGuid() + FileUpload1.FileName);
FileUpload1.SaveAs(ImgPath);
string ShowImgPath = ImgPath.Substring(ImgPath.LastIndexOf("\\"));
imgShow.ImageUrl = "~/Images" + ShowImgPath;
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert(‘Please select a specific image to upload’);", true);
}
}

This is how we can implement File Upload Control in Update Panel using asp.net.

You may also like following asp.net tutorials:

In this tutorial, we learned how to use file upload control in asp.net with below examples:

  • File upload and thumbnail creation in Asp.Net
  • Upload multiple files in Asp.Net file upload control
  • Read file upload control file content in Asp.Net
  • How to implement File Upload Control in Update Panel using asp.net?
Donwload Hub site pdf

Download SharePoint Online Tutorial PDF FREE!

Get update on Webinars, video tutorials, training courses etc.

>