0

Am trying to display an image for the profile of a customer. and the image is stored in blob type in mysql. am using spring mvc with hibernate. i know that to display an image which is blob type, we have to convert into bytes. i did upto some extent. now am stuck that am not able to display any image.

  my controller:
   @RequestMapping(value="/myProfile.htm", method=RequestMethod.GET)

  public ModelAndView Profilelist(HttpServletRequest request,ModelMap model,Customer        
 customer,Profile profile, HttpServletResponse response) throws SQLException , 
 Exception{
    //Profile profile = new Profile();

    String customerName = request.getUserPrincipal().getName();

    customer = customerService.getCustomerId(customerName);
    profile = profileService.getBycustomerId(customer);
    System.out.println("cust:  "+ customer);
    System.out.println("profile:  "+ profile);
    logger.error("Viewing Profile" +customerName);
    //Customer customer = new Customer();



    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buf = new byte[1024];
    /*byte[] encodeBase64 = Base64.encodeBase64(buf);
    String base64Encoded = new String(encodeBase64, "UTF-8");
    ModelAndView mav = new ModelAndView();
    mav.addObject("profile", base64Encoded);*/
    Blob blob = profile.getContent();
    InputStream in = blob.getBinaryStream();
    System.out.println("id content" +in);
    int n = 0;
    while ((n=in.read(buf))>=0)
    {
       baos.write(buf, 0, n);

    }

    in.close();
    byte[] bytes = baos.toByteArray(); 
    System.out.println("bytes" +bytes);
    byte[] encodeBase64 = Base64.encodeBase64(buf);
    String base64Encoded = new String(encodeBase64, "UTF-8");
    ModelAndView mav = new ModelAndView();
    //mav.addObject("content", base64Encoded);
    customer.setEmailId(customerName);
    profile.setCustomer(customer);
    //profile.setContent(blob);
    System.out.println();
    profile = profileService.findProfileById(customer);
    model.addAttribute("content",base64Encoded);

    model.addAttribute("profile", profile);
    mav = new ModelAndView("myProfile");
    return mav;}

And in jsp am calling it as

       <img  src= "data:image/jpeg;bytes,${profile.content}"/>

My jsp is

     <form:form method="GET" modelAttribute="profile" action="myProfile.htm"   
             enctype="multipart/form-data">


            <div class="containerdiv" align="center" >

                   <img  src= "data:image/jpeg;bytes,${content}"/>

                   </div>
   </form:form>

4 Answers 4

1

Persisting Image Blob object on your database is not a good practice. just persist the filename of your image in db and the image itself to a certain path.

I know that this is not what you asking for but If you know how to upload a photo to a specific directory and since you are using spring You can take it as an alternatives.

why dont you create a Controller to read the image for you. see this:

@Controller
public class ImageReadFile{

    // this is for mapping your image related path. 
    @RequestMapping(value="/image/*")
    public void readImage(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        ServletContext sc = request.getServletContext();

        //here i uploaded my image in this path
        String imagePath = "/home/somefolder/Workspaces/Images/";
        String [] fragmentFilename = request.getServletPath().split("/");

        //Check if image isn't set
        if(fragmentFilename.length <= 2){
            return;
        }

        String filename = fragmentFilename[2];
        String requestedImage = "/"+filename;

        if(filename == null){
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        File image = new File(imagePath, URLDecoder.decode(requestedImage, "UTF-8"));

        if(!image.exists()){
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        String contentType = sc.getMimeType(image.getName());
        response.reset();
        response.setContentType(contentType);
        response.setHeader("Content-Length", String.valueOf(image.length()));
        Files.copy(image.toPath(), response.getOutputStream());
    }

}

This is how you gonna diplay the image

<img alt="${profile.filename}" src="${pageContext.request.contextPath}/image/${profile.filename}">

this is how i display the image in my webapp.

Sign up to request clarification or add additional context in comments.

1 Comment

ok i'll try... if it works for me... am very thankful to you...and thank you in advance
1

just use this code in JSP

<img alt="img" src="data:image/jpeg;base64,${content}"/>

there was 'bytes' in <img tag> and I'd got same broken icon. Then I use 'base64' in <img> tag and its work!

Comments

0

Looks like your image still uses blob from profile rather than encoded string. Try using content attribute directly

<img  src= "data:image/jpeg;bytes,${content}"/>

3 Comments

thank you for response... i did what you told...still same issue
am stuck with this from last two days
just an broken image icon is displayed. but when i open that broken image icon in new tab a big url came but that same broken image is coming.
0

You have written some wrong code, let me try to correct it,

Replace

ModelAndView mav = new ModelAndView();
//mav.addObject("content", base64Encoded); 
customer.setEmailId(customerName);
profile.setCustomer(customer);
//profile.setContent(blob); 
System.out.println();
profile = profileService.findProfileById(customer);
model.addAttribute("content",base64Encoded);

model.addAttribute("profile", profile);
mav = new ModelAndView("myProfile");
return mav;}

With

ModelAndView mav = new ModelAndView();
customer.setEmailId(customerName);
profile.setCustomer(customer);
profile = profileService.findProfileById(customer);
mav.addObject("content", base64Encoded);
mav.addObject("profile", profile);   
return mav;
}

4 Comments

i did what you suggested.. same issue... just an broken image icon is displayed on a page. but when i open that broken image icon in new tab a big url came but that same broken image is coming. with an message
"data:image/jpeg;bytes,55SAG3JJJjWSSTP5Co+5dKy0kA/xAiffTjEXr1sD2/swOQzkE8j91ST+taiuIcV9rltosAfH/as/6T/wrDQq+PDApIM+OtNzeVSuXfbeNN+UA+tJLhbgYDL8RHqaZXcPczfdiOZ29OtWmmIsvD7YuuQ+q8lH589PnUXjsGqXSikgzIg7T/xvS3BrwttmcyeszPXypvjmzYlmzSNIKjYbRp0+tbprov8ApHV9n/wkThdp38qFKzMEnl1rla0QiEs4jwp2cQI2oUK8t7OwicDjG9o4Yk6H0g09a9rQoVfIlYkxPEkFe9MeG9JYbGgaKs52G0zYmC0K8S49bt9y0DcunSAJA6kkdKr/ABPtFcxByWhCfygn4jeu4LCXlEW7Rk7s0SfMnl4UAPrl0ALNtw==" because it contains error
this is comming when i open that broken image icon
Right, you are getting this as responce as you are sending the same data from the controller.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.