Fetching attachment by using java and ektorp

200 Views Asked by At

I use java servlet and ektorp for couchdb). I added image to database but i didn't show it.

AttachmentInputStream data = db.getAttachment("document_id","attachment_id");

I fetched attachment by this way. Problem is that i don't know how to show this fetched image in java servlet.

Thank in advance.

1

There are 1 best solutions below

0
AGP On

Basically you need to get output stream of HttpServletResponse and do a buffered write.

String contentType = "image/png";
AttachmentInputStream data = db.getAttachment("document_id","attachment_id");

response.setContentType(contentType);
response.setContentLength(longToInt(data.getContentLength()));
OutputStream out = response.getOutputStream();
byte[] buffer = new byte[1024];
int count = 0;
while ((count = data.read(buffer)) >= 0) {
    out.write(buffer, 0, count);
}
out.close();
data.close();

Copied from link!