渲染图像&使用spring MVC在jsp页面上显示文本

时间:2014-10-20 08:27:55

标签: spring-mvc outputstream

我必须在jsp页面上显示一些细节以及保存在我的计算机驱动器上的图像。

如何使用Spring MVC实现它? 我尝试了以下方法,但它不起作用(是的,我的书面代码是错误的)

@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>

1 个答案:

答案 0 :(得分:2)

如果您想进行最小程度的更改并使其正常工作,您应该对图像进行Base64编码,然后按照以下方式更改标记

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

所以你方法的改变应该是

@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;
}

IOUtils和Base64都来自org.apache.commons,不应该有问题