How to download attachment file from JSP

↘锁芯ラ 提交于 2021-02-10 12:11:26

问题


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 from mail server. The link should be for content dispostion's attachment type. How can I do that in JSP?


回答1:


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.




回答2:


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");




回答3:


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();


来源:https://stackoverflow.com/questions/2727371/how-to-download-attachment-file-from-jsp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!