开发者

How to download attachment file from JSP

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

I want to create a link on JSP page, and by clicking on that link user can download file开发者_如何学Go from mail server. The link should be for content dispostion's attachment type. How can I do that in JSP?


Don't use a JSP for this, it's recipe for trouble when using it to stream binary files, because all whitespace outside the <% %> tags will be printed to the response as well which would only corrupt binary content. All you need to do is to just place a HTML link like <a href="fileservlet/file.ext"> in the JSP and use a servlet class to do all the processing and streaming task. To set a response header, just use HttpServletResponse#setHeader().

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

You can find here a basic servlet example which does exactly this: FileServlet.


I suggest you break this question down a bit.

Do you know how to access the attachments from within a regular java program? How to interface with the mail-server etc? If you know that, it should be an easy exercise to provide the attachment in a downloadable format through jsp. Although, I would strongly recommend you to do a regular servlet, since you would probably not have much use of the extra machinery around jsp.

Just make sure you set the content type according to what's being downloaded:

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

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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜