displaying image stored in database.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sumittyagi
    Recognized Expert New Member
    • Mar 2007
    • 202

    displaying image stored in database.

    Hi! everybody!
    I am facing one problem.
    How to get data from response, where content type is image/jpg ore image/gif.
    normally browser do it for us, when it encounters an image tag, it sends an image request to the server, then reads the response and replaces img tag by image.

    Now what I want to do is as follows:
    step1: send an asynchronous request(request for image) to server.

    step2: server reads the image from database, creates an image response, and returns back result.

    step3: at onreadystate=4, client reads response data, creates image element, and provide response data to image element.

    My problem is at step3.
    as far as I know we can only get response body in two ways from XMLHTTPResponse object, as simple text & second as xml.

    How to get data having MIME type other than text/html & text/xml.

    Its really urgent, any suggession & help will be greatly appreciated.

    Thanks in advance.
  • dmjpro
    Top Contributor
    • Jan 2007
    • 2476

    #2
    i also tried .. but failed .....

    try my code without using AJAX

    [HTML]<html>
    <head>
    <script language = javascript>
    function startPage()
    {
    try
    {
    if(navigator.ap pName.indexOf(' Explorer') != -1)
    {
    /*var request = new ActiveXObject(' Microsoft.XMLHT TP');
    request.open('G ET','https://172.20.0.207/CoalNetPROD/common/html/lov.gif',true);
    request.onready statechange = new function(){
    alert(request.r eadyState);
    if(request.read yState == 4)
    {
    if(request.stat us == 200) alert(request.r esponseText);
    }
    request.send(nu ll);
    }*/

    }
    else{}
    }catch(err){
    alert(err.descr iption);
    }
    }
    </script>
    </head>
    <body onload = startPage()>
    <img id = img1 style = 'width:170px;he ight:130px' src = 'https://172.20.0.207/CoalNetPROD/common/html/lov.gif'></img>
    <input type = button value = " Click Me " onclick = "document.getEl ementById('img1 ').src = 'https://172.20.0.207/CoalNetPROD/common/html/90003781.jpg'">
    </body>
    </html>[/HTML]

    welcome again
    Last edited by acoder; Mar 21 '07, 09:42 AM. Reason: Code in code tags

    Comment

    • acoder
      Recognized Expert MVP
      • Nov 2006
      • 16032

      #3
      It may not be exactly what you want, but this might put you on the right track.

      Comment

      • sumittyagi
        Recognized Expert New Member
        • Mar 2007
        • 202

        #4
        Thanks a lot for your replies.

        A special thanks to acoder, as I have got a hint from the link he provided.

        Originally posted by acoder
        It may not be exactly what you want, but this might put you on the right track.
        Hint is:
        Code:
        ImageEditor.loaderImage.setAttribute("src", "getImage.php?imageName=" + ImageEditor.imageName + "&t=" + (new Date).getTime());
        * that means image tag makes a request to the server according to the src attribute.

        * so I can make a request to server, which will be reading the image from database and writing that to response and setting content type to image/jpg.

        * I think it should work.

        * I will respond back to this thread if it is successful.

        Thanks a lot again!!!!

        Comment

        • sumittyagi
          Recognized Expert New Member
          • Mar 2007
          • 202

          #5
          Originally posted by sumittyagi
          Thanks a lot for your replies.

          A special thanks to acoder, as I have got a hint from the link he provided.



          Hint is:
          Code:
          ImageEditor.loaderImage.setAttribute("src", "getImage.php?imageName=" + ImageEditor.imageName + "&t=" + (new Date).getTime());
          * that means image tag makes a request to the server according to the src attribute.

          * so I can make a request to server, which will be reading the image from database and writing that to response and setting content type to image/jpg.

          * I think it should work.

          * I will respond back to this thread if it is successful.

          Thanks a lot again!!!!

          Yes!!!!
          it worked.

          Thanks a lot to all of you!
          Specially thanks to you acoder!!!!

          Comment

          • sumittyagi
            Recognized Expert New Member
            • Mar 2007
            • 202

            #6
            Originally posted by sumittyagi
            Yes!!!!
            it worked.

            Thanks a lot to all of you!
            Specially thanks to you acoder!!!!

            & I realize that dmjpro also gave a hint, but I was not able to relate it at that point, his hint was:
            <img id = img1 style = 'width:170px;he ight:130px' src = 'https://172.20.0.207/CoalNetPROD/common/html/lov.gif'></img>

            Thanks to you too dmjpro!!!

            Comment

            • acoder
              Recognized Expert MVP
              • Nov 2006
              • 16032

              #7
              Originally posted by sumittyagi
              Yes!!!!
              it worked.

              Thanks a lot to all of you!
              Specially thanks to you acoder!!!!
              You're welcome.

              Comment

              • akirti
                New Member
                • Jan 2008
                • 4

                #8
                i'm doing the same and facing the same problem.

                but the diffenerence is I'm processing the MySQL DB from servlet.

                I'm unable to get image on JSP page.
                as I'm new to ajax so also how this src thing will work with xmlhttpresponse .
                will it be in onload function or requestcall function.
                I'm unable to resolve this issue..
                plz help
                tia

                regards
                kirti

                Comment

                • acoder
                  Recognized Expert MVP
                  • Nov 2006
                  • 16032

                  #9
                  Originally posted by akirti
                  i'm doing the same and facing the same problem.

                  but the diffenerence is I'm processing the MySQL DB from servlet.

                  I'm unable to get image on JSP page.
                  as I'm new to ajax so also how this src thing will work with xmlhttpresponse .
                  will it be in onload function or requestcall function.
                  I'm unable to resolve this issue..
                  Hi kirti, welcome to TSDN!

                  Please post your code (using code tags).

                  Comment

                  • akirti
                    New Member
                    • Jan 2008
                    • 4

                    #10
                    Originally posted by acoder
                    Hi kirti, welcome to TSDN!

                    Please post your code (using code tags).
                    My servlet ----

                    [code=java]
                    package servlet;

                    import java.io.IOExcep tion;
                    import java.io.InputSt ream;
                    import java.sql.Driver Manager;
                    import java.sql.Result Set;
                    import java.sql.SQLExc eption;

                    import javax.servlet.S ervletException ;
                    import javax.servlet.S ervletOutputStr eam;
                    import javax.servlet.h ttp.HttpServlet Request;
                    import javax.servlet.h ttp.HttpServlet Response;

                    import com.mysql.jdbc. Blob;
                    import com.mysql.jdbc. Connection;
                    import com.mysql.jdbc. Statement;

                    public class LeftImageCall extends javax.servlet.h ttp.HttpServlet implements
                    javax.servlet.S ervlet {
                    Connection conn = null;

                    Statement stmt = null;

                    int rowCount, id;

                    public LeftImageCall() {
                    super();
                    }

                    public void init() throws ServletExceptio n {
                    getConnection() ;
                    }

                    public void getConnection() {
                    try {
                    String driver = "com.mysql.jdbc .Driver";
                    String userName = "root";
                    String password = "root";
                    String url = "jdbc:mysql ://localhost:3307/imagetest";
                    System.out.prin tln(url);
                    Class.forName(d river).newInsta nce();
                    conn = (Connection) DriverManager.g etConnection(ur l, userName,
                    password);
                    System.out.prin tln("Database connection established");
                    stmt = (Statement) conn.createStat ement();
                    } catch (Exception sql) {
                    sql.printStackT race();
                    }
                    }

                    public int totalRow() {
                    String query = "select count(" + "*" + ")" + "image_id"
                    + " from left_image_tabl e";
                    try {
                    ResultSet rs1 = stmt.executeQue ry(query);
                    System.out.prin tln(rs1);
                    System.out.prin tln("------------rowcount--left--------");
                    while (rs1.next()) {
                    rowCount = rs1.getInt("ima ge_id");

                    }
                    } catch (SQLException sqle) {
                    sqle.printStack Trace();
                    }
                    return rowCount;
                    }

                    protected void doGet(HttpServl etRequest request,
                    HttpServletResp onse response) throws ServletExceptio n, IOException {
                    int s = totalRow();
                    System.out.prin tln(s);
                    Blob pic_left;
                    String queryleft = "select left_image from left_image_tabl e where image_id="
                    + request.getPara meter("id") + "";
                    ServletOutputSt ream out = response.getOut putStream();
                    try {

                    ResultSet rs = stmt.executeQue ry(queryleft);
                    if (rs.next()) {
                    pic_left = (Blob) rs.getBlob("lef t_image");
                    System.out.prin tln("-------1----------");
                    } else {
                    response.setCon tentType("text/html");
                    System.out.prin tln("-------2---------");
                    out.println("<h tml><head><titl e> Photo</title></head>");
                    out.println("<b ody><h1>No photo for id= "
                    + request.getPara meter("id") + "</h1></body></html>");
                    return;
                    }

                    response.setCon tentType("image/gif");
                    InputStream in = pic_left.getBin aryStream();
                    int length_left = (int) pic_left.length ();
                    System.out.prin tln("-------3----------");
                    int bufferSize = 1024;
                    byte[] buffer = new byte[bufferSize];

                    while ((length_left = in.read(buffer) ) != -1) {
                    System.out.prin tln("writing " + length_left + " bytes");
                    String targetId = request.getPara meter("leftimg" );
                    if (targetId != null)
                    targetId = targetId.trim() .toLowerCase();
                    out.write(buffe r, 0, length_left);
                    System.out.prin tln("-------4-Left---------");
                    }

                    in.close();
                    out.flush();
                    } catch (SQLException err) {
                    response.setCon tentType("text/html");
                    out.println("<h tml><head><titl e>Error: </title></head>");
                    out.println("<b ody><h1>Error=" + err.getMessage( )
                    + "</h1></body></html>");
                    return;
                    }
                    }
                    protected void doPost(HttpServ letRequest request,
                    HttpServletResp onse response) throws ServletExceptio n, IOException{
                    doGet(request,r esponse);
                    }

                    }
                    [/code]

                    My js code for xmlhttp-----


                    [code=javascript]
                    function getXMLHTTPReque st()
                    {
                    var request = false;
                    if(window.XMLHT TPRequest)
                    {
                    request = new XMLHTTPRequest( );
                    }
                    else
                    {
                    if(window.Activ eXObject)
                    {
                    try
                    {
                    request = new ActiveXObjecT(" Msml2.XMLHTTP") ;
                    }
                    catch(err1)
                    {
                    try
                    {
                    request=new ActiveXObject(" Microsoft.XMLHT TP");
                    }
                    catch(err2)
                    {
                    request = false;
                    }
                    }
                    }
                    }
                    return request;
                    }

                    var myRequest = getXMLHTTPReque st();

                    function onload()
                    {
                    var ur =left.src;
                    ur="/LeftImageCall?i d=1";
                    var url = ur+1 ;
                    var myRandom=parseI nt(Math.random( )*999);
                    myRequest.open( "GET", url+"&rand="+my Random, true);
                    myRequest.onrea dystatechange = responseAjaxlef t;
                    myRequest.send( null);
                    }


                    function responseAjaxlef t()
                    {
                    setInterval(onl oad, 10000); // we are only interested in readyState of 4, i.e. “completed”
                    if(myRequest.re adyState == 4)
                    {
                    if(myRequest.st atus == 200)
                    {
                    document.getEle mentById("left" ).innerHTML = myRequest.respo nseText;

                    }
                    else
                    {
                    alert("An error has occurred:"+ myRequest.statu sText);
                    }
                    }
                    }

                    [/code]

                    I'm new to JS and Ajax
                    and really I tried to do this what I learned from the net and few book..
                    please suggest me how to do this,
                    TIA
                    kirti
                    Last edited by gits; Jan 16 '08, 08:22 AM. Reason: fixed code tags

                    Comment

                    • acoder
                      Recognized Expert MVP
                      • Nov 2006
                      • 16032

                      #11
                      Originally posted by akirti
                      I'm new to JS and Ajax
                      and really I tried to do this what I learned from the net and few book..
                      please suggest me how to do this,
                      TIA
                      kirti
                      You don't need the setInterval within the callback function. Have you tried this code without Ajax first?

                      Comment

                      • akirti
                        New Member
                        • Jan 2008
                        • 4

                        #12
                        Originally posted by acoder
                        You don't need the setInterval within the callback function. Have you tried this code without Ajax first?
                        hi,
                        actually I want a constant refresh of iframe image which I'm calling from DB. with the primary key of my DB table called Left_image_tabl e.

                        first problem is I'm unable to get the image in I frame. how I do this?
                        second comes how I can change the key id=1 to n. this is my second task which i think can be dealt with onload function. so I didn't care for this yet.

                        first I want image in my iframe of html page. how I do?
                        please suggest me show me some light plz. is there any problem with DOM or other.

                        I'm sorry for rasing this question again but what I do, I read this thread b4 and unable to get the feel how to do.

                        TIA
                        regards
                        Kirti

                        Comment

                        • acoder
                          Recognized Expert MVP
                          • Nov 2006
                          • 16032

                          #13
                          Originally posted by akirti
                          hi,
                          actually I want a constant refresh of iframe image which I'm calling from DB. with the primary key of my DB table called Left_image_tabl e.

                          first problem is I'm unable to get the image in I frame. how I do this?
                          To get the image into an iframe, you will need to access the iframe first. If you've given your iframe a name, it will appear in the window.frames[] array. Once you have access to the iframe, you will need to access the place where you want to place the image.

                          The reason why you need to move the setInterval out of the callback function is that the function will be called whenever the ready state changes, so you will be making another request after 10 seconds when the ready state is 1, then another when it's 2 and so on. Move it outside the responseAjaxlef t function.

                          Comment

                          • akirti
                            New Member
                            • Jan 2008
                            • 4

                            #14
                            Originally posted by acoder
                            To get the image into an iframe, you will need to access the iframe first. If you've given your iframe a name, it will appear in the window.frames[] array. Once you have access to the iframe, you will need to access the place where you want to place the image.

                            The reason why you need to move the setInterval out of the callback function is that the function will be called whenever the ready state changes, so you will be making another request after 10 seconds when the ready state is 1, then another when it's 2 and so on. Move it outside the responseAjaxlef t function.
                            hi Acoder,
                            I thired to do as u said but still not getting may be I'm worong can u suggest me the chunk of code so that I can read it and get the idea how to do.

                            I tried like:

                            [code=javascript]

                            if(myRequest.st atus == 200)

                            {

                            Window.frames[0].src="../LeftImageCall?i d=1";



                            }
                            [/code]
                            and in html

                            [code=html]
                            <iframe id="response" src="" onoad="onload"> </iframe>
                            [/code]

                            and removed the setinterval...


                            I'm still I dark.
                            may be due to less knowlege of DOM architecture.
                            can u seggest me the exact flow and code how to do this and some basic good books on AJAX,JS and DOM.

                            TIA
                            regards
                            akirti
                            Last edited by acoder; Jan 18 '08, 09:15 AM. Reason: fixed code tags

                            Comment

                            • acoder
                              Recognized Expert MVP
                              • Nov 2006
                              • 16032

                              #15
                              Actually, if you're using an iframe, there's no need for Ajax.

                              Just load the page using the src property into the iframe.
                              Originally posted by akirti
                              can u seggest me the exact flow and code how to do this and some basic good books on AJAX,JS and DOM.
                              The recommended book for JavaScript is David Flanagan's JavaScript : The Definitive Guide. Make sure you get the latest version. Also, check out some of the links in the Offsite Links sticky thread at the top of this forum.

                              Comment

                              Working...