0

So this is the code I have:

public class PdfDownloaderServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
            throws ServletException, IOException {
        httpServletResponse.setContentType("application/pdf");
        ServletContext servletContext = httpServletRequest.getServletContext();
        InputStream inputStream = servletContext.getResourceAsStream("/WEB-INF/classes/pdfs/x.pdf");
        int read;
        byte[] bytes = new byte[1024];
        OutputStream os = httpServletResponse.getOutputStream();
        while ((read = inputStream.read(bytes)) != -1) {
            os.write(bytes, 0, read);
        }
        os.flush();
        os.close();
    }
}

and it works just fine.

However when I click the link that invokes this method, the browser will open the file, but I want the browser to directly download the file. How can I achieve this?

Thanks.

Koray Tugay
  • 22,894
  • 45
  • 188
  • 319

1 Answers1

1

If you want the browser to download as attachment, you need to say so using the Content-Disposition header field. See http://greenbytes.de/tech/webdav/rfc6266.html#disposition.type, disposition type "attachment".

Julian Reschke
  • 40,156
  • 8
  • 95
  • 98