ASP.NET - How to display image in image control

Asked By koteswara rao arvapalli on 19-May-11 03:43 AM
Hai!!!
   I hav a page in that i want to submit the student details with  student photo for that am taking a image control and fileuploader.whenever am uploading the photo in that am not viewing that photo in image control.how can i watch in that control.
I am using .net 2.0 version.
Reena Jain replied to koteswara rao arvapalli on 19-May-11 03:47 AM
hi,

When you are saving or uploading file to your directory on server, it needs Rooted path,but while getting the saved image back we can directly refer that directory and get the uploaded image just after uploading, see the small code snippet

protected void btn_Click(object sender, EventArgs e)
{
   
   if (flUpload.HasFile)
   {
   flUpload.SaveAs(Server.MapPath("Images") + "//" + flUpload.FileName);
   imgUpload.ImageUrl ="Images/" + flUpload.FileName;
   }
}

here flupload.filename is containing the file name which you have uploaded in image folder

Hope this will help you
div v replied to koteswara rao arvapalli on 19-May-11 03:50 AM
Hi,

Try like below code Hope this

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title></title>
</head>
<body>
  <form id="form1" runat="server">
  <div>
  <asp:FileUpload ID="filUpload" runat="server" />
  <asp:Button ID="btnUpload" runat="server" Text="View"
    onclick="btnUpload_Click1"  />
  <asp:Image ID="imgPicture" runat="server" />
   
  <br />
  <asp:Label ID="lblOutput" runat="server" Text="Label"></asp:Label>
  </div>
  </form>
</body>
</html>


Cs.page:

public bool ThumbnailCallback()
  {
  return false;
  }
 
  protected void btnUpload_Click1(object sender, EventArgs e)
  {
  // Initialize variables
 
  string sSavePath;
  string sThumbExtension;
  int intThumbWidth;
  int intThumbHeight;
 
  // Set constant values
 
  sSavePath = "images/";
  sThumbExtension = "_thumb";
  intThumbWidth = 160;
  intThumbHeight = 120;
 
  // If file field isn�t empty
 
  if (filUpload.PostedFile != null)
  {
    // Check file size (mustn�t be 0)
 
    HttpPostedFile myFile = filUpload.PostedFile;
    int nFileLen = myFile.ContentLength;
    if (nFileLen == 0)
    {
    lblOutput.Text = "No file was uploaded.";
    return;
    }
 
    // Check file extension (must be JPG)
 
    if (System.IO.Path.GetExtension(myFile.FileName).ToLower() != ".jpg")
    {
    lblOutput.Text = "The file must have an extension of JPG";
    return;
    }
 
    // Read file into a data stream
 
    byte[] myData = new Byte[nFileLen];
    myFile.InputStream.Read(myData, 0, nFileLen);
 
    // Make sure a duplicate file doesn�t exist.  If it does, keep on appending an
 
    // incremental numeric until it is unique
 
    string sFilename = System.IO.Path.GetFileName(myFile.FileName);
    int file_append = 0;
    while (System.IO.File.Exists(Server.MapPath(sSavePath + sFilename)))
    {
    file_append++;
    sFilename = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
         + file_append.ToString() + ".jpg";
    }
 
    // Save the stream to disk
 
    System.IO.FileStream newFile
      = new System.IO.FileStream(Server.MapPath(sSavePath + sFilename),
             System.IO.FileMode.Create);
    newFile.Write(myData, 0, myData.Length);
    newFile.Close();
 
    // Check whether the file is really a JPEG by opening it
 
    System.Drawing.Image.GetThumbnailImageAbort myCallBack =
         new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
    System.Drawing.Bitmap myBitmap;
    try
    {
    myBitmap = new System.Drawing.Bitmap(Server.MapPath(sSavePath + sFilename));
 
    // If jpg file is a jpeg, create a thumbnail filename that is unique.
 
    file_append = 0;
    string sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
               + sThumbExtension + ".jpg";
    while (System.IO.File.Exists(Server.MapPath(sSavePath + sThumbFile)))
    {
      file_append++;
      sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) +
           file_append.ToString() + sThumbExtension + ".jpg";
    }
 
    // Save thumbnail and output it onto the webpage
 
    System.Drawing.Image myThumbnail
      = myBitmap.GetThumbnailImage(intThumbWidth,
               intThumbHeight, myCallBack, IntPtr.Zero);
    myThumbnail.Save(Server.MapPath(sSavePath + sThumbFile));
    imgPicture.ImageUrl = sSavePath + sThumbFile;
 
    // Displaying success information
 
    lblOutput.Text = "File uploaded successfully!";
 
    // Destroy objects
 
    myThumbnail.Dispose();
    myBitmap.Dispose();
    }
    catch (ArgumentException errArgument)
    {
    // The file wasn't a valid jpg file
 
    lblOutput.Text = "The file wasn't a valid jpg file.";
    System.IO.File.Delete(Server.MapPath(sSavePath + sFilename));
    }
  }
 
  }
Reena Jain replied to koteswara rao arvapalli on 19-May-11 03:50 AM
Hi,
When you are saving or uploading file to your directory on server, it needs Rooted path,but while getting the saved image back we can directly refer that directory and get the uploaded image just after uploading, see the small code snippet

protected void btn_Click(object sender, EventArgs e)
{
     
   if (flUpload.HasFile)
   {
   flUpload.SaveAs(Server.MapPath("Images") + "//" + flUpload.FileName);
   imgUpload.ImageUrl ="Images/" + flUpload.FileName;
   }
}

Here you can see i have just taken back the uploaded image in image control called imgUpload and over there i have not done server.mappath but instead, i have directly refer images directory where image has been uploaded, see the following snapshot of before uploading and after uploading

    

you can see the uploaded image just after uploading.
dipa ahuja replied to koteswara rao arvapalli on 19-May-11 03:52 AM
On the Upload Button Click write the code:
protected void UploadButton1_Click(object sender, EventArgs e)
  {
  if (FileUpload1.HasFile)
  {
    // Code to upload
   
    Image1.ImageUrl = "images/" + FileUpload1.FileName;
  }
}
TSN ... replied to koteswara rao arvapalli on 19-May-11 04:03 AM
hi..

here is the code..


 

When the page first loads, the following code runs:

 

      If Not IsPostBack Then

        imgToView.AlternateText = "Image1"

        imgToView.ImageUrl = "image1.jpg"

      End If

 

You first verify that this is the initial load of the page:

      If Not IsPostBack Then

 

If that is the case, the Image control will display the first image. In that case you set the text of the image to this value:

 

        imgToView.AlternateText = "Image1"

 

Note that this text will appear to visitors when they hover their mouse over the control.

 

 The image URL property is set to the path of the image to be displayed through the Image control:

 

        imgToView.ImageUrl = "image1.jpg"

Jitendra Faye replied to koteswara rao arvapalli on 19-May-11 04:05 AM

Try this....


ASPX -

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


cs 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;  
  }

It will first upload the image to the server...then immediately it will display the same in the image control....

make sure you have images folder in the root directory of the website...

Hope this post helps you...

Anoop S replied to koteswara rao arvapalli on 19-May-11 04:31 AM
Use JavaScript to view the image preview

Image Preview in ASP.NET MVC

  Introduction :

    Previewing an image is a great way to improve the UI of your site. Also it is always best to check the file type, size and see a preview before submitting the whole form. There are some ways to do this using simple JavaScript but not work in all browsers (like FF3).In this Article I will show you how do this using ASP.NET MVC application. You also see how this will work in case of nested form.

  Description :

   Create a new ASP.NET MVC project and then add a file upload and image control into your View.

<form id="form1" method="post" action="NerdDinner/ImagePreview/AjaxSubmit">
      <table>
      <tr>
        <td>
        <input type="file" name="imageLoad1" id="imageLoad1"  onchange="ChangeImage(this,'#imgThumbnail')" />
        </td>
      </tr>
      <tr>
        <td align="center">
        <img src="images/TempImage.gif" id="imgThumbnail" height="200px" width="200px">
        </td>
      </tr>
      </table>
    </form>
 

   Note that here NerdDinner is refers to the virtual directory name, ImagePreview is the Controller and ImageLoad is the action name which you will see shortly

   I will use the most popular jQuery form plug-in, that turns a form into an AJAX form with very little code. Therefore you must get these from Jquery site and then add these files into your page.
 

    <script src="NerdDinner/Scripts/jquery-1.3.2.js" type="text/javascript"></script>
    <script src="NerdDinner/Scripts/jquery.form.js" type="text/javascript"></script>
 

    Then add the javascript function.

<script type="text/javascript">
function ChangeImage(fileId,imageId){
$("#form1").ajaxSubmit({success: function(responseText){
var d=new Date();
$(imageId)[0].src="NerdDinner/ImagePreview/ImageLoad?a="+d.getTime();
}
});
}
</script>


    This function simply submit the form named form1 asynchronously to ImagePreviewController's method AjaxSubmit and after successfully receiving the response, it will set the image src property to the action method ImageLoad. Here I am also adding querystring, preventing the browser to serve the cached image.

          Now I will create a new Controller named ImagePreviewController.

 public class ImagePreviewController : Controller
{
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AjaxSubmit(int? id)
{
Session["ContentLength"] = Request.Files[0].ContentLength;
Session["ContentType"] = Request.Files[0].ContentType;
byte[] b = new byte[Request.Files[0].ContentLength];
Request.Files[0].InputStream.Read(b, 0, Request.Files[0].ContentLength);
Session["ContentStream"] = b;
return Content( Request.Files[0].ContentType+";"+ Request.Files[0].ContentLength );
}
public ActionResult ImageLoad(int? id)
{
byte[] b = (byte[])Session["ContentStream"];
int length = (int)Session["ContentLength"];
string type = (string)Session["ContentType"];
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = type;
Response.BinaryWrite(b);
Response.Flush();
Session["ContentLength"] = null;
Session["ContentType"] = null;
Session["ContentStream"] = null;
Response.End();
return Content("");
}
}

    The AjaxSubmit action method will save the image in Session and return content type and content length in response. ImageLoad action method will return the contents of image in response.Then clear these Sessions.

          Just run your application and see the effect.


Checking Size and Content Type of File:

   You may notice that AjaxSubmit action method is returning both content type and content length. You can check both properties before submitting your complete form.


  $(myform).ajaxSubmit({success: function(responseText)
      {     
      var contentType=responseText.substring(0,responseText.indexOf(';'));
      var contentLength=responseText.substring(responseText.indexOf(';')+1);
      // Here you can do your validation
      var d=new Date();
      $(imageId)[0].src=" /NerdDinner/ImagePreview/ImageLoad?a="+d.getTime();
      }
    });


Handling Nested Form Case:

   The above code will work if you have only one form. But this is not the case always.You may have a form control which wraps all the controls and you do not want to submit the whole form, just for getting a preview effect.

    In this case you need to create a dynamic form control using JavaScript, and then add file upload control to this form and submit the form asynchronously

function ChangeImage(fileId,imageId) {
    var myform=document.createElement("form");
    myform.style.display="none";
    myform.action="/ImagePreview/AjaxSubmit";
    myform.enctype="multipart/form-data";
    myform.method="post";
    var imageLoad;
    var imageLoadParent;
    var is_chrome = /chrome/.test( navigator.userAgent.toLowerCase() );
    if(is_chrome && document.getElementById(fileId).value=='')
        return;//Chrome bug onchange cancel
    if(document.all || is_chrome){//IE
        imageLoad=document.getElementById(fileId);
        imageLoadParent=document.getElementById(fileId).parentNode;
        myform.appendChild(imageLoad);
        document.body.appendChild(myform);
    }
    else{//FF
        imageLoad=document.getElementById(fileId).cloneNode(true);        
        myform.appendChild(imageLoad);
        document.body.appendChild(myform);
    }    
    $(myform).ajaxSubmit({success: 
        function(responseText){            
                var d=new Date();
                $(imageId)[0].src="http://weblogs.asp.net/ImagePreview/ImageLoad?a="+d.getMilliseconds();                
            if(document.all || is_chrome)//IE
                imageLoadParent.appendChild(myform.firstChild);
            else//FF                     
                document.body.removeChild(myform);
        }
    });
}

http://weblogs.asp.net/imranbaloch/archive/2010/04/03/image-preview-in-asp-net-mvc.aspx