Foros de discusión

Writing image application/octet-stream in RenderResponse and display in jsp

thumbnail
Sipin Verma, modificado hace 9 años.

Writing image application/octet-stream in RenderResponse and display in jsp

Junior Member Mensajes: 29 Fecha de incorporación: 14/12/10 Mensajes recientes
Hi All,

I am facing issue in displaying the image (written to RenderResponse) in jsp page. I have to download a image using some webservice call, write it to response & show the image in jsp.

Below are the details:
- From jsp I make ajax calls to ResourceURL passing some id of the image to be downloaded from webservice.
$("#mydiv img").each(function () {
var currentImgSrc = $(this).attr('src');
$(this).attr('id','myImgId');
$.ajax({
type : 'POST',
url : '<%=myResUrl%>'+'&imagePath='+$(this).attr('src'),
async : false,
success : function(data) {
$("#myImgId").attr('src', data);
$("#myImgId").removeAttr('id');
}
});
});

- From serveResource() method call is made to a webservice call to get images as "application/octet-stream"
- After getting image binary, I write this to RenderResponse. Below is the code:
try{
response.reset();
}catch(IllegalStateException e){
log.info("IllegalStateException thrown, unable to reset response");
}
response.setContentType(mimeType);
response.addProperty(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + fileName + "\"");
response.addProperty(HttpHeaders.PRAGMA, "public");
response.setContentLength(in.available());
FileCopyUtils.copy(in,response.getPortletOutputStream());

- Now I use below code to show the image in ajax success part:
$("#myImgId").attr('src', data);

However the image is not getting displayed. Rather I see binary characters in the IMG src. Below is the img tag after rendering:
<img style="HEIGHT: 268px; WIDTH: 775px" alt="linktext" width="100" height="100" src="�PNG


IHDR � F ǃ G sRGB�� � gAMA�� �a pHYs � � �+ /�IDATx^��Mr�ʍ��� �F��� ���� 9�#G��{� �� z �!&quot; ! Y���E�� �&gt;y d � ��^���?���k�Ǔ����?���?���&quot;�^ �� �����W�����O ���7{�� _O~ �Cj\�ɍo���p�3�G��� =����=�m����0U|l ��~�yr��b��7{&gt;�5D��K^��ɫ��޷�E� Y��h�
........ id="aui_1_2_3">

Does anyone have such experience of handling image data? How can I show the image properly in the UI instead of these junk characters.
Let me know if you need more info.
thumbnail
Anil Sunkari, modificado hace 9 años.

RE: Writing image application/octet-stream in RenderResponse and display in

Expert Mensajes: 427 Fecha de incorporación: 12/08/09 Mensajes recientes
Hi Verma,


I did in the below way.It can be helpful.

1) <portlet:resourceURL id="cpt" var="cpt" ></portlet:resourceURL>


2) @SuppressWarnings("unused")
@ResourceMapping(value = "xxx")
public @ResponseBody
void populateCaptcha(final PortletRequest portletRequest, ResourceRequest request, ResourceResponse response) throws IOException {
response.setContentType("image/png");
OutputStream ostream = response.getPortletOutputStream();
NumbersAnswerProducer numCapt = new NumbersAnswerProducer(7);
Captcha captcha = new Captcha.Builder(200, 50).addText(numCapt).addNoise().addBackground(new GradiatedBackgroundProducer()).build();

CaptchaServletUtil.writeImage(PortalUtil.getHttpServletResponse(response), captcha.getImage());
portletRequest.getPortletSession().setAttribute(Captcha.NAME.concat(CommonConstants.VOTE_EVALUATE), captcha);
}

3) <img src="${cpt}" id="captchaImage"/>
thumbnail
Sipin Verma, modificado hace 9 años.

RE: Writing image application/octet-stream in RenderResponse and display in

Junior Member Mensajes: 29 Fecha de incorporación: 14/12/10 Mensajes recientes
Thanks for reply Anil.
In my case the image can be of any type like png, gif, jpeg etc.. So I can't set the content type like you set and have set as "application/octet-stream".
Though I tried one thing- I changed the RenderResponse as below but no success:
HttpServletResponse httpResponse = PortalUtil.getHttpServletResponse(response);
thumbnail
Anil Sunkari, modificado hace 9 años.

RE: Writing image application/octet-stream in RenderResponse and display in

Expert Mensajes: 427 Fecha de incorporación: 12/08/09 Mensajes recientes
Okay,

Other way of writing ....


1)

@ResourceMapping("cpt")
public @ResponseBody
void actionDownloadImage(final BindingResult errors, final ExtendedModelMap model,
final ResourceRequest resourceRequest, final ResourceResponse resourceResponse, final PortletRequest portletRequest) throws IOException {

OutputStream out = null;
resourceResponse.setContentType("application/octet-stream");
out = resourceResponse.getPortletOutputStream();
if (file != null) {
PDDocument document = PDDocument.load(file);
List<PDPage> pages = document.getDocumentCatalog().getAllPages();
for (int i = 0; i < pages.size(); i++) {
PDPage pDPage = pages.get(i);
BufferedImage buffImage =pDPage.convertToImage();
byte[] imageBytes = ((DataBufferByte) buffImage.getData().getDataBuffer()).getData();
out.write(imageBytes);
}
}

}


2)<img src="${cpt}" />
thumbnail
Sipin Verma, modificado hace 9 años.

RE: Writing image application/octet-stream in RenderResponse and display in

Junior Member Mensajes: 29 Fecha de incorporación: 14/12/10 Mensajes recientes
Anil,
The way you mentioned above is working in my code also i.e. If I call the resourceUrl directly in <img> tag like you wrote:
<img src="${cpt}" />
then it works fine for one image.

But as I wrote in my question I have multiple images in my HTML document to download and so I am looping for each <img> tag. If I loop through each <img> and pass the resourceUrl in src like above then also the image is displayed in browser. Below is the code:
$("#mydiv img").each(function () {
$(this).attr('src','<portlet:resourceURL id="streamAttachments"/>'+'&imagePath='+$(this).attr('src'));
});

Originally my code was like this only. But this has one problem; the javascript/jquery resource requests are much faster than the backend processing in java. So most of the times it misses out some of the images to download. Hence, all the images in the loop are not getting downloaded and some are getting missed out.

To fix this I have made a synchronous ajax call (the one I have written in my query post). By this way the resource requests are made sequentially and response is coming in ajax success part. And I am setting the success data in <img> src but it is not getting rendered as image.

I have noted one difference in both (synchronous ajax call & direct img src call) of the ways. If we make resource request like <img src="${cpt}" />, then the resourceUrl is set in the src.
But if we use the ajax call then the streamed binary/octet-stream is set in the src as I explained in my question.

Let me know if you have any idea, how can I display the image from the ajax success response data.
thumbnail
Sipin Verma, modificado hace 9 años.

RE: Writing image application/octet-stream in RenderResponse and display in (Respuesta)

Junior Member Mensajes: 29 Fecha de incorporación: 14/12/10 Mensajes recientes
Finally I had to do this with Servlet by defining servlet mapping in the web.xml and creating my servlet class.
As I was having Sync issue so I had to make my method synchronized in servlet.
KASHYAP DAS, modificado hace 6 años.

RE: Writing image application/octet-stream in RenderResponse and display in

New Member Mensajes: 2 Fecha de incorporación: 28/01/18 Mensajes recientes
Sipin Verma:
Finally I had to do this with Servlet by defining servlet mapping in the web.xml and creating my servlet class.
As I was having Sync issue so I had to make my method synchronized in servlet.


Hi Sipin Verma ,

Can you tell me what changes did you make to web.xml to make that happen .I am also facing the same issue in my code below is my issue details

https://stackoverflow.com/questions/48490465/loading-image-without-storing-it-to-disk-from-a-servlet-with-jquery-asynchronous?noredirect=1#comment83982196_48490465
thumbnail
Jayaram pokuri, modificado hace 9 años.

RE: Writing image application/octet-stream in RenderResponse and display in

New Member Mensajes: 22 Fecha de incorporación: 3/07/13 Mensajes recientes
Hi Verma,

JSP supports text writer only, that's a reason it displays binary data on the page. JSP page looks for the application to open or download when content-type is set with "APPLICATION/OCTET-STREAM" . You should pass "Content-Disposition" that need to set the file type name with image extensions like .png, .jpg. Even though, I am not sure this will work.
As a best practice, persist the image type (PNG, JPEG) also along with image data into table. Webservice call should retrieve the image and type as well and render the image as per above the post that anil posted.

Thanks,
Jayaram