简体   繁体   中英

How do I send an image to the output in JSP

I want to open my servlet which basically checks my permissions and if allowed, shows me a picture like it would be a real jpeg. My code so far:

File file = new File("C:/test.jpeg");
FileInputStream fis = new FileInputStream(file);
byte imageBytes[] = new byte[(int) file.length()];
    
response.setContentType("image/jpeg");
response.setContentLength(imageBytes.length);
response.getOutputStream().write(imageBytes);
response.getOutputStream().flush();

But somehow the image it tries to show me in the browser is corrupted. I already checked that the file exists, as the image.length is not zero. What did I do wrong?

You should start using the newer NIO.2 File API that was added in Java 7, mostly the Files class, because it makes the job much easier.

Option 1: Load file into byte[]

byte[] imageBytes = Files.readAllBytes(Paths.get("C:/test.jpeg"));

response.setContentType("image/jpeg");
response.setContentLength(imageBytes.length);
try (OutputStream out = response.getOutputStream()) {
    out.write(imageBytes);
}

Option 2: Stream the file without using a lot of memory (recommended)

Path imageFile = Paths.get("C:/test.jpeg");
response.setContentType("image/jpeg");
response.setContentLength((int) Files.size(imageFile));
try (OutputStream out = response.getOutputStream()) {
    Files.copy(imageFile, out);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM