I need to open a pdf file for the user who clicks on a download button.
The download button makes a ajax call to a servlet which gets data from a blob field in the database containing PDF contents, and returns it as a response.
What can I do in order to make the response to be downloaded as a PDF file to the user.
The servlet code is as below:
response.setContentType("application/pdf");
oracle.sql.BLOB blob = (BLOB) rs.getBlob("MYPDF");
byte[] bytes = blob.getBytes(1, (int) blob.length());
ServletOutputStream servletOutputStream = response.getOutputStream();
servletOutputStream.write(bytes, 0, bytes.length);
servletOutputStream.flush();
servletOutputStream.close();
I receive a long response containing characters like the ones below in AJAX when I checked the Fire bug for the response.
�a�J��㔎��ji�2K���y�2��q F�f�9�G��!%�kɂ��W��������mp){h̕�S���NJ_�A����'����2k��j���яR�>wB�e�|=w�p�%w��qǦ>�~�1o�㾙9j�B�;aNx3�`z��طc�O��ï��$�;�N|;�xۇ��;�-�c�f�M��c���(�f�M6K���
I don't want to submit the page or to popup a window for the servlet with the parameters se开发者_如何学Cnt for the query showing in the URL
I also don't want to create the file on the server.
Is there a way to take the response of servlet coming in ajax call and display it to a page or Iframe and the browser automatically downloads the file...
Its is NOT possible to download a file using Ajax. However, the same 'effect' can be achieved using a hidden IFRAME. Instead of using XMLHttpRequest, dynamically create a hidden iframe and submit it to the servlet with the proper parameters. When the response comes, the browser will automatically handle the content based on the content-type/extension. If you are using jQuery, then this plugin has this functionality in-built.
Sounds like Rahulmohan knows his stuff but it might be worth trying to add a filename header to your response stream. I do something similar in asp.net but not in an Ajax environment and the only difference between my code and yours is this line:
Response.AddHeader("Content-Disposition", "attachment; filename=" & Filename & ".pdf")
My page doesn't run in an Ajax environment though.
精彩评论