I wrote a series of blog posts awhile back before that demonstrates the following:
- Uploading and Storing Images to Database in ASP.NET
- Displaying Image to Image Control based on User Selection in ASP.NET
- FAQ: Displaying Image from Database to GridView Control
- Uploading and Storing Image Path to Database and Image to Folder - Part 1
- Uploading and Storing Image Path to Database and Image to Folder - Part 2 (Displaying of Images)
- Validate Image extensions upon Upload
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. The folder structure should look something like this below:
Solution
- 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:FileUpload ID="FileUpload1" runat="server" />
- <asp:Button ID="Button1" runat="server" Text="Upload" onclick="Button1_Click"/>
- <br />
- <asp:Image ID="Image1" runat="server" />
- protected void Button1_Click(object sender, EventArgs e) {
- StartUpLoad();
- }
- private void StartUpLoad() {
- //get the file name of the posted image
- string imgName = FileUpload1.FileName;
- //sets the image path
- string imgPath = "ImageStorage/" + imgName;
- //get the size in bytes that
- int imgSize = FileUpload1.PostedFile.ContentLength;
- //validates the posted file before saving
- if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "") {
- // 10240 KB means 10MB, You can change the value based on your requirement
- if (FileUpload1.PostedFile.ContentLength > 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);
- }
- }
- }


Join the conversation! Your thoughts help the community grow.