mi3
mi3

Reputation: 581

writing image to a jsp from database

I am trying to write an image to a jsp from database (saved as BLOB). I am using spring and in my controller, I do have the image byte[].

So I am doing this

byte[] imageBytes = dao.getImage(cc);

model.setAttribute("myimage", new String(imageBytes));

In my jsp, I have

<img src=data:image/jpg;base64,"<c:out value='${myimage}'/>" alt="my image" />

But I only see ascii charcaters in my jsp page (like below).

���K�_&�w:��=5�)^-����O?���R��?�z�i*\�*M�?��1�?�?�]?,��Z�?�I?�P??��?�z�~?v�?�k��?l�M�s�����?E���.��Q��]��?����a?h���e�/?�;�k�]����W�?c�?E���.��Q��]��??麯?~��-�?L��z?�Z�:?6??�z�=��a?��+���e�'�5�����??��?�?C���.�|��w�v?y��-�??U�?��?�D���?�g���ݭ)?A?�? 7��$��??�?�?�]??.���]�S�?�����bO��?L��e��z�h��gzn��?�?�?E���.�?.���]�<�eOO�?S��??� �˰.���]���?�ʿ?��?�?E��?`�]�ֻD��???�\?}U}?�>�T��m��z�h�t����U|E}?K��>�T� |�Q��]���Vd?�Q?�G��E�A�?�˰*�wz�i(sh?�U^�b?�z�~?v�m��Z�i�q?ULf%�L�z�~?v�o�z�i�;!&F�VϨ��?����K�?�u޵�u?��Vxx?�?ѯ��.�>W�[cֻKt��???�����??)e?b�}M�?���g�?h��ѯA/?��J��e�(����3�?����

I even tried to convert the byte[] to ByteArrayOutputStream and encode it with Base64, but didn;t work

model.addAttribute("image", Base64.encode(imageBytes));

But when I write the byte[] to a file(myimage.jpg) using FileOutputStream, I do see the image displayed in my jsp using the old fashioned way

<img src="../images/myimage.jpg" .... />

Upvotes: 7

Views: 7066

Answers (5)

Henry Mac
Henry Mac

Reputation: 41

This is a similar question to the one I was working on. However, I was using long poll instead of servlet. Here is the link stackoverflow.

Upvotes: 0

Sunil
Sunil

Reputation: 492

@RequestMapping(value="/imageDisplays/{imageId}")

public void getImage(@PathVariable int imageId,HttpSession session,HttpServletResponse response)  {
    OutputStream oImage;
    try{
            byte[] imageInByte = // get image in byte array
            response.setContentType("image/jpeg, image/jpg, image/png, image/gif");
            oImage=response.getOutputStream();
            oImage.write(imageInByte);
            oImage.flush();
            oImage.close(); 
    }catch(Exception e){
        LOGGER.debug("Request could not be completed at this moment. Please try again.");
        e.printStackTrace();
    }
    }

Upvotes: 0

CodeChimp
CodeChimp

Reputation: 8154

Another option, if you like using the ModelAndView would be to create a custom View object that sets up the media type and outputs the bytes of the image to the output stream. This way you can use the ModelAndView to easily set redirects or return a normal error or even an JSP error page if there is an error, like image not found.

Upvotes: 0

danny.lesnik
danny.lesnik

Reputation: 18639

Unfortunately it won't work.

You need to use Spring MVC Controller method which will write your your image as byte[] to your HttpServletResponse class.

example:

@RequestMapping("/getImage/{id}")
public void getImage(HttpServletResponse response,@PathVariable("id") final String id) throws IOException {
    response.setContentType("image/jpeg");
    byte[] imageBytes = dao.getImage(id);
    response.getOutputStream().write(imageBytes);
    response.getOutputStream().flush();
}

and then use html code on client:

<img src="getImage/222" ... />

Update: Yes you can do it with @ResposneBody annotation starting from Spring 3.1

Register your ByteArrayHttpMessageConverter

<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter">
            <property name="supportedMediaTypes">
                <list>
                    <value>image/jpeg</value>
                    <value>image/png</value>
                </list>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

And then use yout controller:

@RequestMapping("/getPhoto/{id}")
public @ResponseBody byte[] getPhoto(@PathVariable("id") final String id) throws IOException {
    byte[] imageBytes = dao.getImage(id);
    return imageBytes;
}

Upvotes: 5

Zutty
Zutty

Reputation: 5377

The trick is to have another servlet that outputs the data directly to HttpServletResponse.getOutputStream(), and as SuKu says with the appropriate content type. Then in your JSP you just point to the URL your image servlet is mapped to in the <img/> tag. For instance, if the image servlet is mapped to /imgServlet, you would use something like this

<img src="imgServlet?img=myimage" ... />

Try something like this http://www.avajava.com/tutorials/lessons/how-do-i-return-an-image-from-a-servlet-using-imageio.html

Upvotes: 4

Related Questions