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: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:
protected void Button1_Click(object sender, EventArgs e) {
StartUpLoad();
}
private void StartUpLoad() {
string imgName = string.Empty;
int imgSize = 0;
string imgPath = string.Empty;
if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "") {
imgName = FileUpload1.PostedFile.FileName;
imgPath = "ImageStorage/" + imgName;
imgSize = FileUpload1.PostedFile.ContentLength;
if (imgSize > 10240) {
Page.ClientScript.RegisterClientScriptBlock(typeof(Page),
"Alert", "alert('File is too big.')", true);
} else {
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.