By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,009 Members | 2,821 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,009 IT Pros & Developers. It's quick & easy.

displaying image stored in database.

sumittyagi
Expert 100+
P: 202
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.
Mar 20 '07 #1
Share this Question
Share on Google+
17 Replies


dmjpro
100+
P: 2,476
i also tried .. but failed .....

try my code without using AJAX

[HTML]<html>
<head>
<script language = javascript>
function startPage()
{
try
{
if(navigator.appName.indexOf('Explorer') != -1)
{
/*var request = new ActiveXObject('Microsoft.XMLHTTP');
request.open('GET','https://172.20.0.207/CoalNetPROD/common/html/lov.gif',true);
request.onreadystatechange = new function(){
alert(request.readyState);
if(request.readyState == 4)
{
if(request.status == 200) alert(request.responseText);
}
request.send(null);
}*/

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

welcome again
Mar 20 '07 #2

acoder
Expert Mod 15k+
P: 16,027
It may not be exactly what you want, but this might put you on the right track.
Mar 21 '07 #3

sumittyagi
Expert 100+
P: 202
Thanks a lot for your replies.

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

It may not be exactly what you want, but this might put you on the right track.
Hint is:
Expand|Select|Wrap|Line Numbers
  1. 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!!!!
Mar 21 '07 #4

sumittyagi
Expert 100+
P: 202
Thanks a lot for your replies.

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



Hint is:
Expand|Select|Wrap|Line Numbers
  1. 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!!!!
Mar 23 '07 #5

sumittyagi
Expert 100+
P: 202
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;height:130px' src = 'https://172.20.0.207/CoalNetPROD/common/html/lov.gif'></img>

Thanks to you too dmjpro!!!
Mar 23 '07 #6

acoder
Expert Mod 15k+
P: 16,027
Yes!!!!
it worked.

Thanks a lot to all of you!
Specially thanks to you acoder!!!!
You're welcome.
Mar 23 '07 #7

P: 4
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
Jan 15 '08 #8

acoder
Expert Mod 15k+
P: 16,027
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).
Jan 15 '08 #9

P: 4
Hi kirti, welcome to TSDN!

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

Expand|Select|Wrap|Line Numbers
  1. package servlet;
  2.  
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.sql.DriverManager;
  6. import java.sql.ResultSet;
  7. import java.sql.SQLException;
  8.  
  9. import javax.servlet.ServletException;
  10. import javax.servlet.ServletOutputStream;
  11. import javax.servlet.http.HttpServletRequest;
  12. import javax.servlet.http.HttpServletResponse;
  13.  
  14. import com.mysql.jdbc.Blob;
  15. import com.mysql.jdbc.Connection;
  16. import com.mysql.jdbc.Statement;
  17.  
  18. public class LeftImageCall extends javax.servlet.http.HttpServlet implements
  19.         javax.servlet.Servlet {
  20.     Connection conn = null;
  21.  
  22.     Statement stmt = null;
  23.  
  24.     int rowCount, id;
  25.  
  26.     public LeftImageCall() {
  27.         super();
  28.     }
  29.  
  30.     public void init() throws ServletException {
  31.         getConnection();
  32.     }
  33.  
  34.     public void getConnection() {
  35.         try {
  36.             String driver = "com.mysql.jdbc.Driver";
  37.             String userName = "root";
  38.             String password = "root";
  39.             String url = "jdbc:mysql://localhost:3307/imagetest";
  40.             System.out.println(url);
  41.             Class.forName(driver).newInstance();
  42.             conn = (Connection) DriverManager.getConnection(url, userName,
  43.                     password);
  44.             System.out.println("Database connection established");
  45.             stmt = (Statement) conn.createStatement();
  46.         } catch (Exception sql) {
  47.             sql.printStackTrace();
  48.         }
  49.     }
  50.  
  51.     public int totalRow() {
  52.         String query = "select count(" + "*" + ")" + "image_id"
  53.                 + " from left_image_table";
  54.         try {
  55.             ResultSet rs1 = stmt.executeQuery(query);
  56.             System.out.println(rs1);
  57.             System.out.println("------------rowcount--left--------");
  58.             while (rs1.next()) {
  59.                 rowCount = rs1.getInt("image_id");
  60.  
  61.             }
  62.         } catch (SQLException sqle) {
  63.             sqle.printStackTrace();
  64.         }
  65.         return rowCount;
  66.     }
  67.  
  68.     protected void doGet(HttpServletRequest request,
  69.             HttpServletResponse response) throws ServletException, IOException {
  70.         int s = totalRow();
  71.         System.out.println(s);
  72.         Blob pic_left;
  73.         String queryleft = "select left_image from left_image_table where image_id="
  74.                 + request.getParameter("id") + "";
  75.         ServletOutputStream out = response.getOutputStream();
  76.         try {
  77.  
  78.             ResultSet rs = stmt.executeQuery(queryleft);
  79.             if (rs.next()) {
  80.                 pic_left = (Blob) rs.getBlob("left_image");
  81.                 System.out.println("-------1----------");
  82.             } else {
  83.                 response.setContentType("text/html");
  84.                 System.out.println("-------2---------");
  85.                 out.println("<html><head><title> Photo</title></head>");
  86.                 out.println("<body><h1>No photo for id= "
  87.                         + request.getParameter("id") + "</h1></body></html>");
  88.                 return;
  89.             }
  90.  
  91.             response.setContentType("image/gif");
  92.             InputStream in = pic_left.getBinaryStream();
  93.             int length_left = (int) pic_left.length();
  94.             System.out.println("-------3----------");
  95.             int bufferSize = 1024;
  96.             byte[] buffer = new byte[bufferSize];
  97.  
  98.             while ((length_left = in.read(buffer)) != -1) {
  99.                 System.out.println("writing " + length_left + " bytes");
  100.                 String targetId = request.getParameter("leftimg");
  101.                 if (targetId != null)
  102.                     targetId = targetId.trim().toLowerCase();
  103.                 out.write(buffer, 0, length_left);
  104.                 System.out.println("-------4-Left---------");
  105.             }
  106.  
  107.             in.close();
  108.             out.flush();
  109.         } catch (SQLException err) {
  110.             response.setContentType("text/html");
  111.             out.println("<html><head><title>Error: </title></head>");
  112.             out.println("<body><h1>Error=" + err.getMessage()
  113.                     + "</h1></body></html>");
  114.             return;
  115.         }
  116.     }
  117.     protected void doPost(HttpServletRequest request,
  118.             HttpServletResponse response) throws ServletException, IOException{
  119.         doGet(request,response);
  120.     }
  121.  
  122. }
  123.  
My js code for xmlhttp-----


Expand|Select|Wrap|Line Numbers
  1. function getXMLHTTPRequest()
  2. {
  3.     var request = false;
  4.     if(window.XMLHTTPRequest)
  5.     {
  6.         request = new XMLHTTPRequest();
  7.     } 
  8.     else 
  9.     {
  10.         if(window.ActiveXObject)
  11.         {
  12.             try
  13.             {
  14.                 request = new ActiveXObjecT("Msml2.XMLHTTP");
  15.             }
  16.             catch(err1)
  17.             {
  18.                 try
  19.                 {
  20.                     request=new ActiveXObject("Microsoft.XMLHTTP");
  21.                 }
  22.                 catch(err2)
  23.                     {
  24.                         request = false;
  25.                     }
  26.             }
  27.         }
  28.     }
  29.     return request;
  30. }
  31.  
  32. var myRequest = getXMLHTTPRequest();
  33.  
  34. function onload() 
  35. {
  36.     var ur =left.src;
  37.     ur="/LeftImageCall?id=1";
  38.     var url = ur+1 ;                 
  39.     var myRandom=parseInt(Math.random()*999);        
  40.     myRequest.open("GET", url+"&rand="+myRandom, true);
  41.     myRequest.onreadystatechange = responseAjaxleft;
  42.     myRequest.send(null);
  43. }
  44.  
  45.  
  46. function responseAjaxleft() 
  47. {
  48.      setInterval(onload, 10000);            // we are only interested in readyState of 4, i.e. “completed”
  49.     if(myRequest.readyState == 4) 
  50.     {
  51.         if(myRequest.status == 200) 
  52.         {
  53.             document.getElementById("left").innerHTML = myRequest.responseText;
  54.  
  55.         } 
  56.         else 
  57.         {
  58.             alert("An error has occurred:"+ myRequest.statusText);
  59.         }
  60.     }
  61. }
  62.  
  63.  
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
Jan 16 '08 #10

acoder
Expert Mod 15k+
P: 16,027
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?
Jan 16 '08 #11

P: 4
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_table.

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
Jan 17 '08 #12

acoder
Expert Mod 15k+
P: 16,027
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_table.

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 responseAjaxleft function.
Jan 17 '08 #13

P: 4
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 responseAjaxleft 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:

Expand|Select|Wrap|Line Numbers
  1.  
  2. if(myRequest.status == 200)
  3.  
  4.         {
  5.  
  6.             Window.frames[0].src="../LeftImageCall?id=1";
  7.  
  8.  
  9.  
  10.         } 
  11.  
and in html

Expand|Select|Wrap|Line Numbers
  1. <iframe id="response" src="" onoad="onload"></iframe>
  2.  
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
Jan 18 '08 #14

acoder
Expert Mod 15k+
P: 16,027
Actually, if you're using an iframe, there's no need for Ajax.

Just load the page using the src property into the iframe.
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.
Jan 18 '08 #15

sumittyagi
Expert 100+
P: 202
Expand|Select|Wrap|Line Numbers
  1. response.setContentType("image/gif");
  2.             InputStream in = pic_left.getBinaryStream();
  3.             int length_left = (int) pic_left.length();
  4.             System.out.println("-------3----------");
  5.             int bufferSize = 1024;
  6.             byte[] buffer = new byte[bufferSize];
  7.  
  8.             while ((length_left = in.read(buffer)) != -1) { (No need of while loop, simply 'if' would do the work. i.e. you can replace while with if) 
  9.                 System.out.println("writing " + length_left + " bytes");
  10.                 String targetId = request.getParameter("leftimg");
  11.                 if (targetId != null)
  12.                     targetId = targetId.trim().toLowerCase();
  13.                 out.write(buffer, 0, length_left);
  14.                 System.out.println("-------4-Left---------");
  15. (you forgot to set content length; i.e. response.setContentLength(length_left))  
  16.             }
  17.             in.close();
  18.             out.flush();
  19.         } catch (SQLException err) {
  20.             response.setContentType("text/html");
Jan 20 '08 #16

sumittyagi
Expert 100+
P: 202
Now comming to javascript part:-
Ajax currently returns only two types of responses, XML and text) it doesn't return other format. So you can't use ajax for this purpose, (as you can see from dmjpro's reply).

Now images make their own separate request, so just use images, don't get complicated by using iframes.

<img src="<path to your servlet>" id="target_img">

Now to repeatedly change your image, make a function which changes src of this image.
Expand|Select|Wrap|Line Numbers
  1. function imgRefresh()
  2. {
  3.   var target_image = document.getElementById("target_img");
  4.   target_image.src = "<path to your servlet>"; [here you could use random function to randomly generate this path.]
  5. }
  6.  
Now on onload of the document, call the setInterval function calling above function.
<body onload="setInterval('imgRefresh()', 5000)">

Remember while using setInterval function, time should be set keeping in consideration, the processing time of the called function).

I think this should resolve your problem.
Jan 20 '08 #17

acoder
Expert Mod 15k+
P: 16,027
sumittyagi, I think that should resolve the problem.

Just remember to use those code tags. Thanks!
Jan 20 '08 #18

Post your reply

Sign in to post your reply or Sign up for a free account.