I am new to javascript and i have a requirement where i need to open pdf file on click of submit button which is located on server. Also i need to redirect it to new jsp. I tried using window.open but it did not open as it is not able to fetch file from server location. a href is also not working. can you people suggest me.
Asked
Active
Viewed 203 times
-2
-
1Have a look at this answer: https://stackoverflow.com/questions/32545632/how-can-i-download-a-file-using-window-fetch – chomprrr May 14 '20 at 17:52
-
Why can't you use the href, provide your PDF location to href, it will work but that PDF link should be accessible to your web. – lakshitha madushan May 14 '20 at 18:14
-
@lakshithamadushan since it is a server location, it cannot be accessible to provide as href. Example: tomcat\\temp – Diya May 14 '20 at 18:18
-
@AmerFarooq I tried but did not work – Diya May 14 '20 at 18:22
1 Answers
0
There are different ways to do it, if you are using servlets you can write the right MIME type into the response and write the PDF to the servlet stream
Something like:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/pdf;charset=UTF-8");
response.addHeader("Content-Disposition", "inline; filename=" + "cities.pdf");
ServletOutputStream out = response.getOutputStream();
InputStream inputStream = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
inputStream = new FileInputStream("sourcePath_of_pdf.pdf");
byte[] buffer = new byte[1024];
baos = new ByteArrayOutputStream();
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
baos.write(buffer, 0, bytesRead);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
baos.writeTo(out);
}

Rafael
- 104
- 8