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=
C# HttpClient tutorial C# HttpClient tutorial shows how to create HTTP requests with HttpClient in C#. In the examples, we create simple GET and POST requests. The Hypertext Transfer Protocol (HTTP) is an application protocol for distributed, collaborative, hypermedia information systems. HTTP is the foundation of data communication for the World Wide Web. HttpClient  is a base class for sending HTTP requests and receiving HTTP responses from a resource identified by a URI. C# HttpClient status code HTTP response status codes indicate whether a specific HTTP request has been successfully completed. Responses are grouped in five classes: Informational responses (100–199) Successful responses (200–299) Redirects (300–399) Client errors (400–499) Server errors (500–599) Program.cs using System; using System.Net.Http; using System.Threading.Tasks; namespace HttpClientStatus { class Program { static async Task Main(string[] args) { using var client = new

Popup form on Screen Center Javascript

Popup Form on Center  to popup the form on Screen Center use the below Script Example : <script language="javascript"> var popupWindow = null; function centeredPopup(url,winName,w,h,scroll){ LeftPosition = (screen.width) ? (screen.width-w)/2 : 0; TopPosition = (screen.height) ? (screen.height-h)/2 : 0; settings = 'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',resizable' popupWindow = window.open(url,winName,settings) } </script> <p><a href="http://www.quackit.com/common/link_builder.cfm" onclick="centeredPopup(this.href,'myWindow','500','300','yes');return false">Centered Popup</a></p>