Response fails to return image when outputBuffer bytesWritten < 8kb

落爺英雄遲暮 提交于 2019-12-12 04:08:05

问题


Within a SpringBoot app, I am attempting to return images via a Response object's outputBuffer, via:

try {
    response.setContentType("image/png");
    InputStream in = new FileInputStream(pathToFile);
    IOUtils.copy(in, response.getOutputStream());

}
catch (Exception e){
    ...
}

This works fine, unless the image is less than 8kb, in which case it just returns nothing.

Can anyone tell me why being less than 8kb would cause the Response to actually return zero data (and - crucially - how to remedy this)?


回答1:


I've solved it by setting the content length explicitly in the header:

File actualFile = new File(pathToFile);
if (actualFile.exists()){
    try {
        response.setContentType("image/png");
        response.setHeader("Content-Length", String.valueOf(actualFile.length()));
        InputStream in = new FileInputStream(pathToFile);
        IOUtils.copy(in, response.getOutputStream());
    }
    catch (Exception e){
        ...
    }
}

I guess it didn't like not knowing the size of the content if it was below 8kb.



来源:https://stackoverflow.com/questions/36314082/response-fails-to-return-image-when-outputbuffer-byteswritten-8kb

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