How to load attachment file from JSP

I want to know how to download any file from JSP page based on posting content as attachment from mail server.

I want to create a link in a JSP page, and by clicking on that link, the user can download the file from the mail server. The link must be for the attachment type . How can I do this in JSP?

+2


a source to share


3 answers


Don't use JSP for this, this is a recipe for a problem when using it to stream binary files as all spaces outside the tags <% %>

will be printed and on the response, which will only corrupt the binary content. All you have to do is just place the HTML link, for example <a href="fileservlet/file.ext">

in a JSP, and use the servlet class to do the whole processing and streaming task. To set the response header, just use HttpServletResponse#setHeader()

.

response.setHeader("Content-Disposition", "attachment;filename=name.ext");

      



Here you can find a basic example of a servlet that does just this: FileServlet

.

+4


a source


I suggest you break this question down a bit.

Do you know how to access attachments from a regular Java program? How to interact with the mail server, etc.? If you know this, it should be a simple exercise to provide downloadable format nesting via jsp. Although, I would highly recommend that you make a regular servlet, since you probably wouldn't use the additional technique around jsp very much.

Just make sure you set the content type to match what you downloaded:



In jsp: <%@page contentType="image/png" %>

In a servlet: response.setContentType("image/png");

0


a source


URL url = new URL("http://localhost:8080/Works/images/abt.jpg");

            //for image 
            response.setContentType("image/jpeg");
            response.setHeader("Content-Disposition", "attachment; filename=icon" + ".jpg");

            //for pdf
            //response.setContentType("application/pdf");
            //response.setHeader("Content-Disposition", "attachment; filename=report" + ".pdf");

            //for excel sheet
            //  URL url = new URL("http://localhost:8080/Works/images/address.xls");
            //response.setContentType("application/vnd.ms-excel"); 
            //response.setHeader("Content-disposition", "attachment;filename=myExcel.xls");


            URLConnection connection = url.openConnection();
            InputStream stream = connection.getInputStream();

            BufferedOutputStream outs = new BufferedOutputStream(response.getOutputStream());
            int len;
            byte[] buf = new byte[1024];
            while ((len = stream.read(buf)) > 0) {
                outs.write(buf, 0, len);
            }
            outs.close();

      

0


a source







All Articles