Here is a very simplified solution. The idea is to make a form message, not just a GET.
<head> <script type="text/javascript"> function openFile(fileName) { document.getElementById('filename').value = fileName; document.getElementById('viewform').submit(); } </script> </head> <body> <a id="view" class="btn btn-info btn-xs" href="javascript:openFile('<%=rs.getString(2)%>');">click me</a> <form id="viewform" action="Attached-Proof" target="_blank" method="post"> <input type="hidden" name="filename" id="filename" value=""/> </form> </body>
A simple old form entry will still show the file path. To prevent this, on the server side, you define a resource to read the file and write it back to the response. A simple servlet can do the job.
web.xml:
<servlet> <servlet-name>view-file</servlet-name> <servlet-class>com.example.ViewFileServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>view-file</servlet-name> <url-pattern>/Attached-Proof</url-pattern> </servlet-mapping>
And the servlet will look something like this:
package com.example; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ViewFileServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/pdf"); File file = new File(getServletContext().getRealPath(request.getParameter("filename"))); InputStream is = null; try { is = new FileInputStream(file); byte[] buffer = new byte[1024]; int count; while ((count = is.read(buffer)) > 0) { response.getOutputStream().write(buffer, 0, count); } } finally { if (is != null) is.close(); } } }
source share