ASP.NET - Image upload using FIle upload control

Asked By kiran Kumar
08-Dec-11 09:24 AM
hi,

  in my asp.net web application, i have taken one webform named "Default2.aspx", in the design view, i have placed one Image control and one file upload control, now i want to upload an image(jpg, jpeg, bitmap/any format) ! 


  If i select an image through the file upload control, then that image have to be displayed in Image control! how to do this?? 

pls give any solution! i m using Visual studio 2010!
  Riley K replied to kiran Kumar
08-Dec-11 09:48 AM

In the button click you can write this code to show image in Image control

if (fileUpload1.HasFile)
   {
   fileUpload1.SaveAs(Server.MapPath("Images") + "//" + fileUpload1.FileName);
   imgCtrl.ImageUrl ="Images/" + fileUpload1.FileName;
   }

Regards
  Suchit shah replied to kiran Kumar
08-Dec-11 09:49 AM
Try below code

//in aspx:

<asp:FileUpload ID="FileUpload1" runat="server" />
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
        <asp:Image ID="Image1" runat="server"/ >


//in code

protected void Button1_Click(object sender, EventArgs e)
    {
        string path = Server.MapPath("images/") + FileUpload1.PostedFile.FileName;
        FileUpload1.SaveAs(path);
        Image1.ImageUrl = "images/"+FileUpload1.PostedFile.FileName;
    
}


Check out if having any difficulty let me know

 
  Suchit shah replied to kiran Kumar
08-Dec-11 09:53 AM

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

ASPX:

   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. 

CODE BEHIND:

 

   1:  protected void Button1_Click(object sender, EventArgs e) {
   2:              StartUpLoad();
   3:          }
   4:   
   5:          private void StartUpLoad() {
   6:              //get the file name of the posted image
   7:              string imgName = FileUpload1.FileName;
   8:              //sets the image path
   9:              string imgPath = "ImageStorage/" + imgName;          
  10:              //get the size in bytes that
  11:   
  12:              int imgSize = FileUpload1.PostedFile.ContentLength;
  13:              
  14:              //validates the posted file before saving
  15:              if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "") {
  16:                  // 10240 KB means 10MB, You can change the value based on your requirement
  17:                  if (FileUpload1.PostedFile.ContentLength > 10240) {
  18:                      Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Alert", "alert('File is too big.')", true);
  19:                  }
  20:                  else {
  21:                      //then save it to the Folder
  22:                      FileUpload1.SaveAs(Server.MapPath(imgPath));
  23:                      Image1.ImageUrl = "~/" + imgPath;
  24:                      Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Alert", "alert('Image saved!')", true);
  25:                  }
  26:   
  27:              }
  28:          }

 

As you can see the code above is very straight forward and self explanatory.

  kiran Kumar replied to Suchit shah
08-Dec-11 09:56 AM
hi suchit, i wrote in the button click as follows:


        string path = Server.MapPath("images/") + FileUpload1.PostedFile.FileName;
        FileUpload1.SaveAs(path);
        Image1.ImageUrl = "images/" + FileUpload1.PostedFile.FileName;


after debugging, if i select one image from my Folder( "E:\Images\image001"))

  it is showing the error " Couldnot find a part of the path "E:\Images\image001" 

 how to resolve this? 
  kiran Kumar replied to Suchit shah
08-Dec-11 10:12 AM
hi suchit, i tried this one also....

   //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);
                    //}
                }

it is showing the error " File is too big" even i selected the 520 kb image! if i remove that if cluse in the code and tried again ! then it is showing the error message " could not find a part of the path .." E:\Images\image002" 
how to solve this?? 
  Suchit shah replied to kiran Kumar
08-Dec-11 10:20 AM
To resolve this Error just create one directory( folder) name called "images" inside your project and  then run the application

what my mean to say ... if for example is located in E:\Practice\Sample\Asp.net\Lab1 say this is the path of your application

so inside this you have 2 thing 1) Lab1.sln file which is the solution file (2) folder called Lab1 inside this you have all foder for App_code , bin like that so inside this project directory create one more directory called images and then run the project it works

why need to create this directory because we save the image inside this folder and then we are displaying 
if you check the line called Server.MapPath("images/") this line say that we are saving inside our current project directory we have folder called images inside that we save this file


Hope with all this explanation you get my point
  kiran Kumar replied to Suchit shah
08-Dec-11 10:48 AM
hi suchit, i tried this one also....

   //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);
                    //}
                }

it is showing the error " File is too big" even i selected the 520 kb image! if i remove that if cluse in the code and tried again ! then it is showing the error message " could not find a part of the path .." E:\Images\image002" 
how to solve this?? 
  kiran Kumar replied to Suchit shah
08-Dec-11 11:12 AM
suchit..

  even that it is showing the error "Could not find a part of the path 'E:\kirans\TSI\AdminPages\ImageStorage\amazing2.jpg'." 


  i have created directory "ImageStorage" in the project folder 

pls giv solution for this error! i did everything as u said but still the same error is coming yar, check it n give me solution
  Suchit shah replied to kiran Kumar
08-Dec-11 11:26 AM
This error is coming because

 // 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);
                    }

here in comment as i right 10240KB that was my mistake it 10240 Byte means it allowed only 10 KB file size ... so if file is more than 10 KB then it give the error file is too big so now just to make it file size limit upto 1 MB max just do the change in code like below

  // 1048576 Byte means 1MB, You can change the value based on your requirement
                    if (FileUpload1.PostedFile.ContentLength > 1048576) {
                        Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Alert", "alert('File is too big.')", true);
                    }
just do it like this change then after this solution also works..... and yes one more thing if you get any trouble more i suggest one more thing to do the change as per code

In this solution we have do it like below one

string imgPath = "ImageStorage/" + imgName; 
and in else part to save the image we do it like

FileUpload1.SaveAs(Server.MapPath(imgPath));

so before testing the code create one Directory ( Folder) called ImageStore inside the application directory same like we create a directory called "Image" in my previous ( 1st solution)

Hope now you have got both of the solution well...still any concern just let me know






  Suchit shah replied to kiran Kumar
08-Dec-11 11:29 AM
For both of the solution you need to create a different directory name

for the 1st solution you need to create a directory name called "Image"
for the 2nd solution you need to create a directory name called "ImageStore"


This both solution perfectly working I have tested both the solution on my machine with creating this directory name
  dipa ahuja replied to kiran Kumar
08-Dec-11 12:06 PM
try this code. This will save your file in the images folder and if the image file already exist then it wil rename it.
 
<asp:FileUpload ID="FileUpload1" runat="server"></asp:FileUpload>
<asp:Button ID="UploadButton" Text="Upload file" OnClick="UploadButton_Click" runat="server"/>
 
 
protected void UploadButton1_Click(object sender, EventArgs e)
{
  if (FileUpload1.HasFile)
  {
    // Call a helper method routine to save the file.
    // Specify the path to save the uploaded file to.
    string savePath = Server.MapPath("images/");
 
    // Get the name of the file to upload.
    string fileName = FileUpload1.FileName;
 
    // Create the path and file name to check for duplicates.
    string pathToCheck = savePath + fileName;
 
    // Create a temporary file name to use for checking duplicates.
    string tempfileName = "";
 
    // Check to see if a file already exists with the, same name as the file to upload.      
    if (File.Exists(pathToCheck))
    {
      int counter = 2;
      while (File.Exists(pathToCheck))
      {
        // if a file with this name already exists,
        // prefix the filename with a number.
        tempfileName = counter.ToString() + fileName;
        pathToCheck = savePath + tempfileName;
        counter++;
      }
 
      fileName = tempfileName;
 
      // Notify the user that the file name was changed.
      UploadStatusLabel.Text = "A file with the same name already exists." +
        "<br />Your file was saved as " + fileName;
    }
    else
    {
      // Notify the user that the file was saved successfully.
      UploadStatusLabel.Text = "Your file was uploaded successfully.";
    }
 
    // Append the name of the file to upload to the path.
    savePath += fileName;
    FileUpload1.SaveAs(savePath);
     
    Image1.ImageUrl = "images/" + FileUpload1.FileName;
  }
  else
  {
    // Notify the user that a file was not uploaded.
    UploadStatusLabel.Text = "You did not specify a file to upload.";
  }
}
 
  Anoop S replied to kiran Kumar
08-Dec-11 02:04 PM
With the FileUpload control, it can be done with a small amount of code lines, as you will see in the following example. However, please notice that there are security concerns to to consider when accepting files from users! Here is the markup required:
<form id="form1" runat="server">
    <asp:FileUpload id="FileUploadControl" runat="server" />
    <asp:Button runat="server" id="UploadButton" text="Upload" onclick="UploadButton_Click" />
    <br /><br />
    <asp:Label runat="server" id="StatusLabel" text="Upload status: " />
</form>

And here is the CodeBehind code required to handle the upload:

protected void UploadButton_Click(object sender, EventArgs e)
{
    if(FileUploadControl.HasFile)
    {
        try
        {
            string filename = Path.GetFileName(FileUploadControl.FileName);
            FileUploadControl.SaveAs(Server.MapPath("~/") + filename);
            StatusLabel.Text = "Upload status: File uploaded!";
        }
        catch(Exception ex)
        {
            StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
        }
    }
}
  kiran Kumar replied to Anoop S
09-Dec-11 05:42 AM
hi anoop

  i have created one directory with the name "Images" in my project! and i wrote the code as u also said , as follows:
 Upload button_click..

  if (FileUpload1.HasFile)
        {
            try
            {
                string filename = Path.GetFileName(FileUpload1.FileName);
                FileUpload1.SaveAs(Server.MapPath("~/images") + filename);
                Label26.Text = "Upload status: File uploaded!";
            }
            catch (Exception ex)
            {
                Label26.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
            }
        }

after debugging, i have selected one image through browse option from my local machine, and if i click on Upload button, it is showing the message : "Upload status: File uploaded!"   if i check in the images folder, there is no image saved at all! what to do? and the image which was saved in the location i have to show in the "image" control! How to do this? the image is not saving but showing the message as uploaded



  kiran Kumar replied to dipa ahuja
12-Dec-11 02:25 AM
hi dipa,
 

   i have used the code which u sent to me, and after some changes,(i have created one folder named Images in the project to store the images to be uploaded into image control)  the image is uploading into image control successfully... at the same time image was storing in that Images folder in the project.

  in my button click i wrote the code as follows for storing that image into database:

  sqlconnection con=new sqlconnection("connstring");
  con.open();
  sqlcommand cmd=new sqlcommand("insert into picture_example values('"+image1.Imageurl+"')",con);
  cmd.ExecuteNonQuery();
  con.close();

  and if i check in the database Picture_example table it was storing in <binary> format!   

  Now, i want to call the image which was stored in database Picture_example table in to Image2 control. How to do this?? pls tell me the code.
  dipa ahuja replied to kiran Kumar
12-Dec-11 02:29 AM
You are going wrong way, if you are storing images in the images folder and also images in the binary format that will increase the size of you database unnecessarily.

So choose  :

Store image name in database(nvarchar databtype) and image files in the images folder
OR
Store only images in the binary format which will contains the actual image no need to store files in the database.

Now its easy to retrieve the image is you go with first option,

but i m telling you the way how to get the binary image from the table:

Step 1: Add a handle in your website and write this code in ProcessRequest:
public void ProcessRequest (HttpContext context)
{
  SqlConnection con = new SqlConnection();
  con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
 
  // Create SQL Command
 
  SqlCommand cmd = new SqlCommand();
  cmd.CommandText = "Select pname,images from Photos where id =@id";
  cmd.CommandType = System.Data.CommandType.Text;
  cmd.Connection = con;
 
  SqlParameter ImageID = new SqlParameter("@id", System.Data.SqlDbType.Int);
  ImageID.Value = context.Request.QueryString["id"];
  cmd.Parameters.Add(ImageID);
  con.Open();
  SqlDataReader dReader = cmd.ExecuteReader();
  dReader.Read();
  context.Response.BinaryWrite((byte[])dReader["images"]);
  dReader.Close();
  con.Close();
}
 
Step 2: Add a Image Control in ItemTemplate:
 
<ItemTemplate>
  <asp:Image ID="Image1" runat="server"
ImageUrl='<%# "Handler.ashx?id=" + Eval("id")%>'/>
</ItemTemplate>
 
//display image from the database using handler
Image2.ImageUrl = "Handler.ashx?id=2";
 
 
  Anoop S replied to kiran Kumar
12-Dec-11 04:17 AM

it is showing the message : "Upload status: File uploaded!"   if i check in the images folder, there is no image saved at all....

Well it is not a huge problem. The problem is that visual studio does not refresh the folder. Hence you need to manually refresh it by right clicking the folder and then clicking refresh or Click the Refresh button at the top of your Solution Explorer.Secondly even if it does not show up in VS that does not mean user will not be able to see it. User will be able to see it becaus file is on disk the issue is that VS does not refresh its folders 

Create New Account
help
alot var Hi What are Master Pages in ASP.NET? or What is a Master Page? ASP.NET master pages allow you to create a consistent layout for the pages in your application. A single master page defines the look and feel and standard behavior that you want for all of the you want to display. When users request the content pages, they merge with the master page to produce output that combines the layout of the master page with the content from the content page. What are the 2 important parts of a master page? The following are the 2 important parts of a master page 1. The Master Page itself 2. One or more Content Pages Can Master Pages be nested? Yes, Master Pages
controls are created and data is provided. . . . but if users select less text box then error occurs that " no. of rows specified or columns specified does not match". . . . . . . . . . HOPE you all Unit6, @Rate6, @Amt6, @DiscAmt, @StAmt, @VatAmt, @AVatAmt, @NetTotal)", con); cmd4.Parameters.Add(new SqlParameter("@Name", SqlDbType.VarChar)); cmd4.Parameters.Add(new SqlParameter("@Address", SqlDbType.VarChar)); cmd4.Parameters.Add(new SqlParameter("@VNo", SqlDbType.Int)); cmd4.Parameters.Add(new SqlParameter("@VDate", SqlDbType.DateTime)); cmd4.Parameters.Add(new SqlParameter("@BillNo SqlDbType.Int)); cmd4.Parameters.Add(new SqlParameter("@Remark", SqlDbType.VarChar)); cmd4.Parameters.Add(new SqlParameter("@ItemName1", SqlDbType.VarChar)); cmd4.Parameters.Add(new SqlParameter("@Qty1", SqlDbType.Float)); cmd4.Parameters.Add(new SqlParameter("@Pcs1
renders the same css differently. Very odd. Sir also some other features : in our profile page we are not able to see the symbol of answer unchecked, checked , ignored, 3* , 1 just missed that feature. Sir, now most of things are working fine as expected ! Profile page , My Post Page etc working good ! site looks great ! Sir one thing i notice . . Every posts has the asp-net / 17 / 10371909 / gridview-sorting-using-jquery.aspx Navigation menu missing in forum merit page http: / / www.eggheadcafe.com / forummerit.aspx Regards Hi Robbe, I suggest you that, if you hi. . previously there is dropdownlist in which we used to select number of posts per page . . . but in the New site it is missing. . . . hi. . . check out the belowlines 2 Replies each Answer posted Hi Robbe, After giving replay for the question and submitting the button, page is showing the top of the page. My suggestion is if the page shows the answer which we have replied wiil be better. hi. . in the below link
object sender, EventArgs e) { FileInfo imageInfo = new FileInfo(File1.Value.Trim()); if (!imageInfo.Exists) this.RegisterClientScriptBlock("alertMsg", "<script> alert('please select one image file.');< / script> "); else { switch (imageInfo.Extension.ToUpper()) { case break; case ".GIF": this.UpLoadImageFile(imageInfo); break; case ".BMP": this.UpLoadImageFile(imageInfo); break; default: this.RegisterClientScriptBlock("alertMsg", "<script> alert('file type error.');< / script> "); break; } } } private void UpLoadImageFile(FileInfo info) { SqlConnection objConn = null; SqlCommand objCom = null; try { byte SqlCommand("insert into Categories(CategoryName, Picture)values(@CategoryName, @Picture)", objConn); SqlParameter categorynameParameter = new SqlParameter("@CategoryName", SqlDbType.NVarChar); if (this.txtFileName.Text.Trim().Equals("")) categorynameParameter.Value = "Default"; else categorynameParameter.Value = this.txtFileName.Text.Trim(); objCom.Parameters.Add(categorynameParameter); SqlParameter pictureParameter = new SqlParameter("@Picture", SqlDbType.Image); pictureParameter.Value = content; objCom.Parameters.Add(pictureParameter); objConn.Open(); objCom.ExecuteNonQuery(); objConn.Close(); } catch strConnectionString); SqlCommand Command = new SqlCommand("select * from Categories order by CategoryID DESC", objConn); objConn.Open(); SqlDataReader MyReader = Command.ExecuteReader(CommandBehavior.CloseConnection); if (MyReader.HasRows = = true) { MyReader.Read(); Response.ContentType = "text / HTML"; Response.BinaryWrite((byte[])MyReader["Picture"]); } else { this.RegisterClientScriptBlock("alertMsg", "<script> alert('No Image.');< / script> "); } MyReader.Close(); } catch (Exception ex) { throw new Exception(ex created globally to avoid having to create and destroy them over and over for each page scanned. For both the scanning object and OCR object, you must call the StartUp function