Missing Bottom part of image using getResponse().getOutputStream().write

青春壹個敷衍的年華 提交于 2019-12-13 05:14:03

问题


i got the image from post response

PostMethod post = new PostMethod(action);
HttpClient httpClient = createHttpClient();

........

httpClient.executeMethod(post);


try {
            log.info("post successfully");
            String contentType = post.getResponseHeader("Content-type").getValue();
            int contentLength = (int) post.getResponseContentLength();
            byte[] responseBody = FileUtils.convertInputStreamtoByteArray(post.getResponseBodyAsStream());
            log.info("get response sucessfully : size "+ responseBody.length +" contentLength " + contentLength);
            return new ReturnBean(null, responseBody,contentType,contentLength);
        } catch (Exception e) {
            log.error(e.getMessage());
            log.error(e.getStackTrace());
            e.printStackTrace();
            throw new ResponseFailedException(e.getMessage());
        }

this is how i convert inputstream to byte array.

public static byte[] convertInputStreamtoByteArray(InputStream is){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            byte[] buf = new byte[1024];
            int i = 0;
            while ((i = is.read(buf)) >= 0) {
                baos.write(buf, 0, i);
            }
            is.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return baos.toByteArray();
    }

this is how i return the image as a response.

byte[] imageSource = (byte[])returnStream.getBean();
            log.info("imageSource " + imageSource.length);
            getResponse().setContentType((String) returnStream.getBean2());
            getResponse().setContentLength((Integer) returnStream.getBean3());
            getResponse().getOutputStream().write(imageSource);
            getResponse().getOutputStream().flush();

i was able to print out the image but im having a problem because the bottom part of it is missing . i checked the size of byte that i got and it is equal to the size of actual image.


回答1:


when i used IOUtils.copyLarge(); instead of my method convertInputStreamtoByteArray

ServletOutputStream outputStream = getResponse().getOutputStream();
            InputStream inputStream = (InputStream) returnStream.getBean();
            IOUtils.copyLarge(inputStream , outputStream);

it works . i dont know what happen because i used it a while ago and it didnt work.



来源:https://stackoverflow.com/questions/34738815/missing-bottom-part-of-image-using-getresponse-getoutputstream-write

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!