1

I have seen answers how to write jpg as response. I would like to write both html and jpg.

What I have now:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<h1 style='text-align:center;'> Welcome to our BookStore </h1>");
    out.println("<p style='text-align:center;'><img src='book_store_image.jpg' alt='books img' style='width:304px;height:228px;'></p>");
    out.println("<form style='text-align:center;'>" +
    "<a href='" + request.getContextPath() + "/books'>Buy books</a><br/><br/>" +
    "<a href="+ request.getContextPath() + "/sellerPage'>Sell books</a>" +
    "</form>");
}

I know I cannot fetch image by doing <img src='book_store_image.jpg'

Question:

Should I open several output streams for it: one for setContentType("text/html"); and one for img?

Community
  • 1
  • 1
Rudziankoŭ
  • 10,681
  • 20
  • 92
  • 192
  • 1
    "I know I cannot fetch image by doing ` – ManoDestra Jul 13 '16 at 13:13
  • You seem to be asking one question but actually desire the answer to another question. Yes, you can use the `data:image/…` method, but I think all you really want is to do is *resolve* you image urls to where they can be viewed from the server. – JayC Jul 13 '16 at 13:49

2 Answers2

4

Transfer the image base64 encoded and use data:image/...;base64 in the src attribute of the img tag.

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />

See Data URI Scheme

René Link
  • 48,224
  • 13
  • 108
  • 140
1

For every request one answer.

So serve the html. If the new HTML contains a new image, give it an URL for a servlet that produces the image.

If the image is one the same page, the request made, should have been an AJAX call, just changing the image on the page, and maybe some text.

If it would be to cumbersome to have a second request for a dynamic image, you could write an embedded <img src=[BASE64 IMAGE DATA]> - that is quite monstrous: 120 KB in Base64 is 160 KB text.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138