0

I want to convert image into byte[] and send it through servlet. I have converted image to byte[] but send it to client ??

protected void doGet(HttpServletRequest request, HttpServletResponse response) 
    throws ServletException, IOException {

    String name=request.getParameter("name");
    File f = new File("/Users/shilu/MyProject/Chat/Photo/" + name);
    byte[] data = Files.readAllBytes(f.toPath());
    //What to do now??
}
1
  • what kind of image ? png, jpg...? Commented Nov 4, 2016 at 11:59

1 Answer 1

1

It depends on the type of image as you need to specify the content type that matches with your image type.

So here assuming that you want to send a png, the code could be something like this:

// Set the media type matching with my image
response.setContentType("image/png");
// Write the data
try (OutputStream out = response.getOutputStream()) {
    out.write(data);
}
Sign up to request clarification or add additional context in comments.

3 Comments

The flush() is unnecessary though, as the implicit close() will also perform a flush.
@Kayaman I was wondering if it was needed or not, I don't see it clearly in the doc of OutputStream#close() that it would be necessarily flushed on close even if by experience I know that it will, it may be implementation specific, don't you agree?
I'd be hesitant to say that it's implementation specific. I would say that a poorly designed stream would discard the bytes instead of flush them, but OutputStream doesn't specify any behaviour. However FilterOutputStream which is essentially the superclass of all custom OutputStreams does flush on close and state that it does so. I wouldn't bother writing overcareful code in cases like these, but YMMV.

Your Answer

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