1

I'm developing an application with jquerymobile and Spring MVC. I'm getting an image in a controller as Inputstream and the next step is to pass this image to Javascript for show in a dialog with JqueryMobile.

How can I pass this java Inpustream image to javascript?

PS. The controller is called throught jquerymobile ajax so i have onSuccess method waiting to make something with returned data from controller.

Jav_Rock
  • 22,059
  • 20
  • 123
  • 164
Hugo
  • 179
  • 5
  • 14
  • seems to me like you need to extract the raw bytes... then, take a look at [this](http://stackoverflow.com/questions/4564119/javascript-convert-byte-to-image), it might be helpful – Less Oct 05 '12 at 11:08
  • 1
    Why do you need to pass image using ajax? Why don't use regular request -> create image url with all dynamic params. Eg test.com/getImage/id13.png (getImage.png?id=13) – zvez Oct 05 '12 at 11:12
  • **Less**, thanks I will take a look. **Zvezdochet**, I'm poping up this retrieval image in a jquerydialog that's I'm using ajax call – Hugo Oct 05 '12 at 11:22

3 Answers3

0

Why not load that image from java using Jquery on a div?

var url = 'myimage.com/image_java_url?'+dataToSend
$('#myDiv').load(url, function(response, status, xhr) {
    if (status = "success"){
        $('#myDiv').html(response);
    }
});
PbxMan
  • 7,525
  • 1
  • 36
  • 40
  • That's would be an option if I gets the image in a URL but I have it in an inputstream – Hugo Oct 05 '12 at 11:41
0

I assume you are creating a REST-endpoint to recieve an image. If so, you could make your Spring-endpoint take HttpServletResponse as an argument and stream the image out to the servlet outputstream. Wrap the inputstream in a BufferedInputStream for to let it handle the buffering for you.

To get hold of the HttpServletResponse just add it as an argument to your method,

@RequestMapping(value = "/something")
public void helloWorld(HttpServletResponse response)  {
    InputStream imageStream = .....;

    OutputStream oSteam = response.getOutputStream();
    InputStream stream = new BufferedInputStream(imageStream ); 
    int b = -1;
    while((b = stream.read())> -1){
        oSteam.write(b);
    }
0

I haven't had much experience with Spring, but I would use the javax.ws.rs.core.Reponse class in Java EE. This will allow you to construct a http response using Response.ResponseBuilder, wrapping your InputStream.

i.e.

Response.ok(inputStream, MEDIA_TYPE.APPLICATION_OCTET_STREAM).build();
wulfgarpro
  • 6,666
  • 12
  • 69
  • 110