Click here to Skip to main content
15,884,176 members
Articles / Programming Languages / C#
Tip/Trick

ASP.NET WebForms: Uploading, Validating And Displaying of Image

Rate me:
Please Sign up or sign in to vote.
5.00/5 (5 votes)
5 Aug 2016CPOL2 min read 13.2K   8  
This tip demonstrates how to upload an image to a specified folder within the root of the web application and display the image right away in the Image control after uploading.

Introduction

Many years ago, I wrote a series of blog posts that demonstrates the following:

In this post, I'm going to demonstrate how to upload an image to a specified folder within the root of the web application and display the image right away in the Image control after uploading.

To get started, let's go ahead and fire up Visual Studio and create a new Website/Web Application project. After that, create a folder under the root application for storing the uploaded images.

Using the Code

The folder structure should look something like this below:

  • Application Name
  • AppCode
  • AppData
  • ImageStorage - //we will save the images in this folder
  • Default.aspx
  • web.config

For the simplicity of this demo, I just set up the HTML form like below:

ASP.NET
<asp:FileUpload ID="FileUpload1" runat="server" />  
<asp:Button ID="Button1" runat="server" 
Text="Upload" onclick="Button1_Click"/>  
<br />  
<asp:Image ID="Image1" runat="server" />  

And here's the code for uploading:

C#
protected void Button1_Click(object sender, EventArgs e) {  
             StartUpLoad();  
}  
     
private void StartUpLoad() {  
        string imgName = string.Empty;  
        int imgSize = 0;
        string imgPath = string.Empty;       
       
       //validates the posted file before saving  
        if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "") {  
              //get the file name of the posted image           
              imgName = FileUpload1.PostedFile.FileName; 
               //sets the image path           
              imgPath = "ImageStorage/" + imgName; 
              //get the size in bytes that  
              imgSize = FileUpload1.PostedFile.ContentLength;  
              // 10240 KB means 10MB, You can change the value based on your requirement  
                if (imgSize > 10240) {  
                           Page.ClientScript.RegisterClientScriptBlock(typeof(Page), 
                           "Alert", "alert('File is too big.')", true);  
                 }  else {  
                           //then save it to the Folder  
                           FileUpload1.SaveAs(Server.MapPath(imgPath));  
                           Image1.ImageUrl = "~/" + imgPath;  
                           Page.ClientScript.RegisterClientScriptBlock(typeof(Page), 
                           "Alert", "alert('Image saved!')", true);  
                }    
          }  
}  

The code above is pretty much self-explanatory, but it think it should be worth explaining what the code does. The StartUpload() method contains the logic for saving the uploaded image to the specified folder location, which is under Project Root/ImageStorage. It also handles couple of basic validations for checking the PostedFile and ContentLength. If the validation fails, then it will trigger an alert popup to let the end user know that something is wrong, otherwise it will save the file to the system and then set the uploaded path as the ImageUrl of the Image control.

That simple! Now you should be able to see the image in the page after uploading.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
United States United States
A code monkey who loves to drink beer, play guitar and listen to music.

My Tech Blog: https://vmsdurano.com/
My Youtube Channel: https://www.youtube.com/channel/UCuabaYm8QH4b1MAclaRp-3Q

I currently work as a Solutions Architect and we build "cool things" to help people improve their health.

With over 14 years of professional experience working as a Sr. Software Engineer specializing mainly on Web and Mobile apps using Microsoft technologies. My exploration into programming began at the age of 15;Turbo PASCAL, C, C++, JAVA, VB6, Action Scripts and a variety of other equally obscure acronyms, mainly as a hobby. After several detours, I am here today on the VB.NET to C# channel. I have worked on Web Apps + Client-side technologies + Mobile Apps + Micro-services + REST APIs + Event Communication + Databases + Cloud + Containers , which go together like coffee crumble ice cream.

I have been awarded Microsoft MVP each year since 2009, awarded C# Corner MVP for 2015, 2016,2017 and 2018, CodeProject MVP, MVA, MVE, Microsoft Influencer, Dzone MVB, Microsoft ASP.NET Site Hall of Famer with All-Star level and a regular contributor at various technical community websites such as CSharpCorner, CodeProject, ASP.NET and TechNet.

Books written:
" Book: Understanding Game Application Development with Xamarin.Forms and ASP.NET
" Book (Technical Reviewer): ASP.NET Core and Angular 2
" EBook: Dockerizing ASP.NET Core and Blazor Applications on Mac
" EBook: ASP.NET MVC 5- A Beginner's Guide
" EBook: ASP.NET GridView Control Pocket Guide

Comments and Discussions

 
-- There are no messages in this forum --