通过servlet不显示完整图像。它底部不完整

时间:2013-08-12 10:22:47

标签: java servlets

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.info("Inside Upload Image Preview---");

    String imageName = request.getParameter("imgName");
    String contentType = "image/";

    BufferedInputStream input = null;
    BufferedOutputStream output = null;

    logger.info("Inside Upload Image Preview---Before try block.");

    try {
        String imageExt = imageName.substring(imageName.lastIndexOf(".")+1);
        logger.info("conent Type for the response is "+contentType);
        logger.info("Image name  is "+imageName);

        contentType = contentType + imageExt;
        response.setContentType(contentType);

        String dirPath= System.getProperty(AMPortletConstants.JBOSS_HOME_DIR)+"/image/";
        File fileName = new File(dirPath+imageName);

        FileInputStream fileInputStream = new FileInputStream(fileName);
        input = new BufferedInputStream(fileInputStream);
        output = new BufferedOutputStream(response.getOutputStream());

        byte[] buffer = new byte[8192];
        for (int length = 0; (length = input.read(buffer)) > 0;) {
            output.write(buffer, 0, length);
        }

        logger.info("Image added in response.");
    } catch (Exception exception) {
        logger.error("Exception in UploadImagePreview======="+exception);
        exception.printStackTrace();
    }   
}

Web.xml中

<servlet>
    <servlet-name>imagePreview</servlet-name>
<servlet-lass>com.xxxxxx.portlet.UploadImagePreview</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>imagePreview</servlet-name>
    <url-pattern>/xxxxxxImages/*</url-pattern>  
</servlet-mapping>

我们点击的网址格式

  

/xxxxxxxx-portlet/xxxxxxImages/img?imgName=Test.png

它在浏览器中显示图像,但问题是图像不完整。小底部缺失。请提供解决方案。

1 个答案:

答案 0 :(得分:0)

你错过了

finally
{
    output.flush();
    output.close();
}

实际上close()会调用flush(),但关于您的问题的重要部分是缺少流的刷新。永远记得close()你的资源,或者你因为资源泄漏而陷入了伤害的世界: - )

干杯,