Matt
Matt

Reputation: 65

HttpServletResponse write multiple images to OutputStream (in the same query)

here is what I'm trying to do:

In my spring controller I am generating a chart on the fly when the request is received. I want to set in the OutputStream of HttpServletResponse an image like "Please wait while loading" while the chart is being generated.

What is happening now is that the browser receives the "Please wait while loading", but never updates to the actual chart. I debugged the code and the chart is written to the OutputStream, but the browser does not load it.

I can't have client-side scripts.

Thanks

@RequestMapping("/img/**")
public void img(HttpServletRequest request, HttpServletResponse response, ChartRequest request) {

        ServletOutputStream os = null;
        try {
            os = response.getOutputStream();
            response.setContentType("image/png");    
                     os.write(base64PNGToByte(ImageContainer.PNG_PLEASE_WAIT)); // here is the "PLEASE WAIT WHILE LOADING" image
            os.flush(); // browser receives the image

                ChartResponse chartResponse = chartManager.processChart(request);
                if (!chartResponse .isSuccess()) {
                    os.write(base64PNGToByte(null));
                    return;
                }

                String base64Img = chartResponse .getResponse();
                os.write(base64PNGToByte(base64Img)); // the generated chart image, but browser does not shows this image...
            } else {
                os.write(base64PNGToByte(null));
            }

            os.flush();
        } catch (IOException e) {
            logger.debug("img: IOException ", e);
        }
    }

Upvotes: 2

Views: 1685

Answers (1)

Nikos Paraskevopoulos
Nikos Paraskevopoulos

Reputation: 40298

A servlet cannot generate two distinct responses like you want.

However it would be much easier to use an <img> with background set to a static "Please wait" image, centered; when the actual image is generated, the background will be overwritten:

<img src="your/dynamic/url?data=123"
   style="background-image: url('path/to static/please-wait.png');
   background-position: 50% 50%; background-repeat: no-repeat;"
/>

(the styles may need to be adjusted, but something along those lines is feasible)

Upvotes: 3

Related Questions