图像无法正确呈现

时间:2013-10-30 23:31:37

标签: java image http java-ee

此代码似乎正常工作,但当我使用它从数据库渲染图像时,页面上的图像不完整。仅渲染了前70%的图像。使用不同的图像渲染不同数量的图像。

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    FileData fileData = new FileData();
    int id = Integer.parseInt(request.getParameter("id"));
    UploadFile uploadFile = fileData.SelectFile(id);
    inputStream = uploadFile.data;
    fileName = uploadFile.name;
    if(uploadFile.Type.equals("Image/Video"))
    {
        contentType = "image";
    }
    render(request, response);
}
private void render(ServletRequest request, ServletResponse response) throws IOException {
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        int inputStreamLength = 0;
        int length = 0;
        while ((length = inputStream.read(buffer)) > -1) {
            inputStreamLength += length;
            baos.write(buffer, 0, length);
        }

        if (inputStreamLength > contentLength) {
            contentLength = inputStreamLength;
        }
        if (response instanceof HttpServletResponse) {
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.reset();
            httpResponse.setHeader("Content-Type", contentType);
            httpResponse.setHeader("Content-Length", String.valueOf(contentLength));
            httpResponse.setHeader("Content-Disposition", "\"" + contentDisposition +
                                   "\"" + (fileName != null && !fileName.isEmpty()) !=
                                   null ? "; filename=\"" + fileName + "\"": "");
        }

        response.getOutputStream().write(baos.toByteArray(), 0, (int)contentLength);

        //finally
        response.getOutputStream().flush();

        //clear
        baos = null;
    }
    finally {
        close(response.getOutputStream());
        close(inputStream);
    }
}
private void close(Closeable resource) throws IOException {
    if (resource != null) {
        resource.close();
    }
}

以下是Firefox中页面在页面上的显示方式示例。 rendered image

我已经检查过上传到网站后图像没有损坏,图像在数据库中没问题。问题是在网站上呈现图像的代码。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

好吧我解决了,显然变量不会在新页面加载时重置,即使它们不是静态的。