0

I have stored my image as mediumblob in database

In my Image bean class I have store photo property as byte[] like

private byte[] photo;

// getter and setter method for photo

I get image from database using to store in Image bean class

image.setPhoto(resultset.getBinaryStreams(1));

then i get the image in Servlet as:

InputStream input = null;
OutputStream output = null;
try {
    input = new ByteArrayInputStream(image.getPhoto());

    output = // What type of stream should I use here

    byte[] buffer = new byte[10240];
    int length;
    while ((length = input.read(buffer)) > 0) {
        output.write(buffer, 0, length);
    }
} finally {
    output.flush();
    input.close();
}

Questions:

  1. WHat should I write at output line to show photo using response.getOutputStream or something else?
  2. Is this method correct or is there any better way?

1 Answer 1

1

Your output stream can be that stream returned by response.getOutputStream() directly. Just be sure to flush the stream after writing all the data to it.

If your servlet container isn't buffering output streams, you can consider wrapping the output in a BufferedOutputStream.

Sign up to request clarification or add additional context in comments.

4 Comments

Not only does the servlet container buffer, it writes to a ByteArrayOutputStream, so it can compute the Content-Length header. You don't have to buffer yourself.
I have done this ServletOutputStream output = response.getOutputStream(); and getting NPE Exception at output.flush();
Are you able to write to it before the call to flush()?
Well, if I had to guess, I'd say that the line input = new ByteArrayInputStream(image.getPhoto()); is failing. Either because image is null or image.getPhoto() returns null. Your finally block should be check both input and output for null since they are null outside the try/finally block.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.