Reputation: 417
I have to show some details on jsp page along with image which is saved on my computer drive.
How can I achieve it using Spring MVC? I have tried the following way but it is not working(yeah, my written code is wrong)
@RequestMapping(value = "/detailsPage", method = RequestMethod.GET)
@ResponseBody
public ModelAndView viewAPIs(@RequestParam("id") Long id, HttpServletResponse res) throws Exception {
ModelAndView mav = new ModelAndView("detailsPage");
if (apiId != null) {
Details obj = detailsService.getObjById(id);
try {
String fileName = obj.getStructurePath();
OutputStream outputStream = res.getOutputStream();
InputStream is = new FileInputStream(new File(fileName));
int readBytes = 0;
byte[] buffer = new byte[10000];
while ((readBytes = is.read(buffer, 0, 10000)) != -1) {
outputStream.write(buffer, 0, readBytes);
}
outputStream.close();
is.close();
// add outputString to model and show it is on page
mav.addObject("structure", outputStream );
} catch (Exception e) {
e.printStackTrace();
}
mav.addObject("obj", obj);
return mav;
}
return null;
}
JSP:
<div class="type">
<p>Structure</p>
<div><img alt="img" src="${structure }"/></div>
</div>
Upvotes: 1
Views: 1108
Reputation: 28559
If you want to do minimal changes an make it work, you should do Base64 encoding of your image and than change the tag as follows
<img alt="img" src="data:image/jpeg;base64,${structure }"/>
So the change in your method should be
@RequestMapping(value = "/detailsPage", method = RequestMethod.GET)
@ResponseBody
public ModelAndView viewAPIs(@RequestParam("id") Long id) throws Exception {
ModelAndView mav = new ModelAndView("detailsPage");
if (apiId != null) {
Details obj = detailsService.getObjById(id);
try {
String fileName = obj.getStructurePath();
byte[] binaryData = IOUtils.toByteArray(new FileInputStream(fileName));
byte[] encodeBase64 = Base64.encodeBase64(binaryData);
String base64Encoded = new String(encodeBase64, "UTF-8");
// add outputString to model and show it is on page
mav.addObject("structure", base64Encoded);
} catch (Exception e) {
e.printStackTrace();
}
mav.addObject("obj", obj);
return mav;
}
return null;
}
both IOUtils and Base64 are from org.apache.commons, shouldn't have a problem finding
Upvotes: 2