Response fails to return image when outputBuffer b

2019-09-04 01:36发布

问题:

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.