开发者

How to send an image from Java-serverside, and handle it on JQuery-clientside

开发者 https://www.devze.com 2023-04-13 05:49 出处:网络
I want to rescale an image and return it to the client, and am running into some trouble with sending the image back to the client.

I want to rescale an image and return it to the client, and am running into some trouble with sending the image back to the client.

My serverside controller:

@RequestMapping(value = {"/fw/ajax/submit_profileimage.do"})
public void submitFile(HttpServletRequest request, HttpServletResponse response, @RequestParam("file") MultipartFile f) {
    try {
        InputStream in = new ByteArrayInputStream(f.getBytes());
        BufferedImage originalImage = ImageIO.read(in);
        BufferedImage newImage = new BufferedImage(MAX_HEIGHT, MAX_WIDTH, BufferedImage.TYPE_INT_RGB);
        paintComponent(newImage.getGraphics(), originalImage, getRatio(originalImage));

        ImageIO.write(newImage, "png", response.getOutputStream());
        response.setContentType("image/png");
        response.getOutputStream().flush();
        response.getOutputStream().close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

Clientside Jquery code:

uploadButton.click(function(){
    $('#imagePreview').addClass('loading');
    form.ajaxSubmit(function(data){
    alert(data); //this is where I'd like to handle the image!
    });
});

the data that is returned by the ajaxSubmit is:

"<body style="margin: 0px;"><img style="-webkit-user-select: none" src="http://localhost:8080/fairview/ajax/submit_profileimage.do"></body>"

Clearly not an image file. But when I check the debugger, I can see that the submit_profileimage.do request has succeded, and allegedly returned 开发者_开发技巧an image! I have no idea if I've done something wrong on the clientside, or on the serverside.

How to send an image from Java-serverside, and handle it on JQuery-clientside

How to send an image from Java-serverside, and handle it on JQuery-clientside

So the question is: How can I display the image on the clientside?


I would simply save the resized image on the server and return back to jquery simpy a URL to where the resized image has been saved. Then simply set the src attribute of the image to that URL. The browser will than take care of downloading the image.

uploadButton.click(function(){
    $('#imagePreview').addClass('loading');
    form.ajaxSubmit(function(data){
        //Assuming data is the URL to the resized image.
        $("#myimage").attr("src", data);
    });
});


I went with the approach described as the accepted answer here: Help getting image from Servlet to JSP page

Which pretty much means I didn't really answer the initial question, I still can't handle a raw image clientside. Rather, I use one service to store the image, return the id of where the image is stored, and set the src attr of the image to a service that will return the image.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号