I want to serve an image to a client by converting it to a byte but for some reason byteArrayOutputStream.toByteArray() is empty. I get a response status of 200 which means it is served. I looked at various documentations on reading an image file from a directory using BufferedImage and then converting BufferedImage to a byteArray from oracle
CodePudding user response:
You should just read the bytes of the file directly rather than using more methods than necessary. This can be done with the class java.nio.file.Files
.
byte[] contentBytes = Files.readAllBytes(path); //Throws IOException
CodePudding user response:
Probably the file extension is not getting set properly.
You can create a new method to get the file extension or you can use FilenameUtils.getExtension
from Apache Commons IO.
public static Optional<String> getExtensionByStringHandling(String filename) {
return Optional.ofNullable(filename)
.filter(f -> f.contains("."))
.map(f -> f.substring(filename.lastIndexOf(".") 1));
}
then change your ImageIO to take this file extention.
String fileExtention= getExtensionByStringHandling(file.getName()).orElseThrow(()->new RuntimeException("File extension not found"));
ImageIO.write(image, fileExtention, byteArrayOutputStream);