I wrote a series of blog posts awhile back before 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. 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:

  1. <asp:FileUpload ID="FileUpload1" runat="server" />
  2. <asp:Button ID="Button1" runat="server" Text="Upload" onclick="Button1_Click"/>
  3. <br />
  4. <asp:Image ID="Image1" runat="server" />
And here's the code for uploading the image to a folder.
  1. protected void Button1_Click(object sender, EventArgs e) {
  2. StartUpLoad();
  3. }
  4. private void StartUpLoad() {
  5. //get the file name of the posted image
  6. string imgName = FileUpload1.FileName;
  7. //sets the image path
  8. string imgPath = "ImageStorage/" + imgName;
  9. //get the size in bytes that
  10. int imgSize = FileUpload1.PostedFile.ContentLength;
  11. //validates the posted file before saving
  12. if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "") {
  13. // 10240 KB means 10MB, You can change the value based on your requirement
  14. if (FileUpload1.PostedFile.ContentLength > 10240) {
  15. Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Alert", "alert('File is too big.')", true);
  16. } else {
  17. //then save it to the Folder
  18. FileUpload1.SaveAs(Server.MapPath(imgPath));
  19. Image1.ImageUrl = "~/" + imgPath;
  20. Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Alert", "alert('Image saved!')", true);
  21. }
  22. }
  23. }
That simple! Now you should be able to see the image in the page after uploading.