Skip to main content

Binding the image Control with bytes


Binding the image Control with byte

 File upload control on client side show image using byte array


//File upload control on change to post the method

fileupload control  and image control should be in update panel

<asp:FileUpload ID="FileUpload1" runat="server"  onchange="this.form.submit();"/>



image control on page

// on page load 


if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.
ContentLength > 0)
        {
            UploadImage();        
        }



// upload image method

 void UploadImage()
    {
        //Session["File"] = fluPicture.FileBytes;
        //Session["Name"] = fluPicture.FileName;

        // string scanletterFileName = "";


        string  letterUploadFileName = System.IO.Path.GetFileName(FileUpload1 .PostedFile.FileName);
        try
        {
            string[] fileType = FileUpload1 .PostedFile.FileName.Split('.');
            int letterI = fileType.Length;
            byte[]  letterUpload = new byte[FileUpload1 .PostedFile.ContentLength];
            if (fileType[letterI - 1].ToUpper().Trim() == "PDF" || fileType[letterI - 1].ToUpper().Trim() == "DOC" || fileType[letterI - 1].ToUpper().Trim() == "JPG" || fileType[letterI - 1].ToUpper().Trim() == "GIF" || fileType[letterI - 1].ToUpper().Trim() == "JPEG" || fileType[letterI - 1].ToUpper().Trim() == "XLS")
            {
                letterUpload = new byte[FileUpload1 .PostedFile.ContentLength];
                HttpPostedFile Image = FileUpload1 .PostedFile;
                Image.InputStream.Read(letterUpload, 0, (int)FileUpload1.PostedFile.ContentLength);
                lblmsg.Text = letterUploadFileName;
                Session["image"] = letterUpload;
                Session["filename"] = letterUploadFileName;

                //lblScanLetter.Text = letterUploadFileName;
                //Response.Redirect("ShowImage.aspx?image=" + letterUpload + "&filename=" + letterUploadFileName);
                //img.ImageUrl="showimage.aspx?image="+letterUpload+"&filename="+ letterUploadFileName.Trim()+"";
                img.ImageUrl = "ShowImage.aspx";
            }

        }
        catch (Exception ex)
        {
            lblmsg.Text = "An Error Occured. Please Try Again!" + ex.Message;
        }

        finally
        {

        }
    }





//showimage.aspx

//on page load


byte[] myimage = (byte[])Session["image"];

        string filename = Session["filename"].ToString();

        FillbinaryData(myimage , filename);





//FillbinaryDate metho


protected void FillbinaryData(byte[] image,string Filename)
    {        
        try
        {
           // Dcon.OpenConnection();

            // drHeads = t1.ExecuteDReader(searchQuery, Dcon.GetConnection);
           // drHeads = t1.ExecuteDReader(searchQuery, Dcon.GetConnection);

           // while (drHeads.Read())
            //{
              //  Response.ClearContent();
               // Response.ClearHeaders();
                if (image != null )
                {
                    string[] contentType = Filename.ToString().Split('.');

                    int i = contentType.Length;
                    switch (contentType[i - 1].ToUpper().Trim())
                    {
                        case "PDF":
                            Response.ContentType = "application/pdf";
                            Response.AddHeader("content-disposition", "attachment;filename=Tr.pdf");
                            break;
                        case "DOC":
                            Response.ContentType = "application/vnd.ms-word";
                            Response.AddHeader("content-disposition", "attachment;filename=Tr.doc");
                            break;
                        case "DOCX":
                            Response.ContentType = "application/vnd.ms-word";
                            Response.AddHeader("content-disposition", "attachment;filename=Tr.doc");
                            break;
                        case "XLS":
                            Response.ContentType = "application/vnd.ms-excel";
                            Response.AddHeader("content-disposition", "attachment;filename=Tr.xls");
                            break;
                        case "XLSX":
                            Response.ContentType = "application/vnd.ms-excel";
                            Response.AddHeader("content-disposition", "attachment;filename=Tr.xls");
                            break;

                        default:

                            break;
                    }
                    byte[] buffer = null;
                    buffer = (byte[])image  ;
                    Response.Charset = "";
                    Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    Response.BinaryWrite(buffer);
                    Response.End();
                }
                else
                    Response.Write("No Data with Specified Request");

            //}

        }
        catch (Exception ex)
        {
            lblmsg.Text = ex.ToString();
        }
        finally
        {
            //drHeads.Close();
            //Dcon.CloseConnection();

        }
    }

Comments

  1. use below code to the Image Preview ( Temporary )

    Javascript :

    Step 1 :
    function uploadImage(ctr)
    {
    var ar= ctr.value.split('.');
    var conType=ar[ar.length-1];
    if(conType.toLowerCase() == 'jpg' && ctr.files.item(0).size < 1024000 )
    {
    ctr.form.submit();
    }
    else
    {
    alert('Image Should be jpg format and Size less than 1 MB');
    }

    }

    Step 2 :



    Step 3 : onpage load

    if (FileUpload1.HasFile)
    {
    UploadedFile objUploadedFile = new UploadedFile();
    objUploadedFile.FileBytes = FileUpload1.FileBytes;
    objUploadedFile.FileName = FileUpload1.FileName;
    Session["UploadedFile"] = objUploadedFile;
    Image1.ImageUrl = "ImagePreview.aspx";
    }

    Step 4 : in ImagePreview.aspx form on load event

    UploadedFile objUploadedFile = (UploadedFile)Session["UploadedFile"];
    Response.ContentType = ".jpg";
    Response.BinaryWrite(objUploadedFile.FileBytes);
    Response.End();


    Step 5 :UploadedFile.cs (Class File)

    public byte[] FileBytes { get; set; }
    public string FileName { get; set; }


    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete

Post a Comment

Popular posts from this blog

PNR Status by web Scraping Method (ASP.NET) C#

To Get the PNR Status by web Scraping Method Steps to Execute the Function Step 1 : Add the below method in your Form and Pass the PNR Number arguement public string GetPNRStatus( string sPNR) { string URI = "http://www.indianrail.gov.in/cgi_bin/inet_pnrstat_cgi.cgi" ; string Parameters = Uri .EscapeUriString( "lccp_pnrno1=" +sPNR+ "&amp;submitpnr=Get Status" ); System.Net. HttpWebRequest req = ( HttpWebRequest )System.Net. WebRequest .Create(URI); //HTTP POST Headers req.ContentType = "application/x-www-form-urlencoded" ; req.Host = "www.indianrail.gov.in" ; //You can use your own user-agent. req.UserAgent = "Mozilla/5.0 (compatible; MSIE 7.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0) DELL;Venue Pro" ; req.Headers.Add( HttpRequestHeader .AcceptLanguage, "en-us,en;q=0.5" ); req.Headers.Add( HttpRequestHeader .AcceptCharset, "ISO-8859-1,utf-8;q=...

SonarQube Configuration For .NET Core Web API

When multiple developers are working on the same project, it's good to have a code review. SonarQube is a tool through which we can evaluate our code. Here, for demo purposes, we are going to evaluate the web API which is built on .NET Core. Let's see step by step implementation. In order to run SonarQube, we need to install JAVA in our local system.   Refer to the below link to download JAVA installer and install JAVA. https://www.oracle.com/technetwork/java/javase/downloads/index-jsp-138363.html Configure the 'PATH' system variable under environment variables Go to Control Panel > System > Advanced System Settings, it will open the System Properties window. Click on the "Environment Variables" button. Click on the "View" button under User Variables. Give the variable name as 'JAVA_HOME'. The variable value will be your JDK path where you installed JAVA. Select path variable under system variable and click o...

Automate Git Commands Across Repos Using Batch Scripts

  Writing Scripts to Apply Commands Across Repositories I store all of my local repositories in a particular directory. I wrote these scripts to automate one or more git commands to run on each repository within that directory. It could also be used to do a general clean-up before committing anything to your repository. Here are two ways to do it. Method 1: Use this when you want to store commands in a single file to be executed in sequence for every repo in your directory. 1 @echo off 2 ​ 3 for /d %%i in (%cd%\*) do ( 4 echo ************************************************************************* 5 ​ 6 echo "%%i" 7 cd "%%i" 8 ​ 9 echo ----------------------------------------- 10 echo status 11 git status 12 echo ----------------------------------------- 13 ​ 14 echo ************************************************************************* 15 ) 16 ​ 17 cd .. 18 ​ The script is simple: It’s composed of a single for loop. W...