日期:2014-05-16  浏览次数:20406 次

JSP文件下载超简单方法,只需要一个apach包
找了N多的下载方法,这个个人感觉是最方便的,传入两个参数,全路径和文件名,也可以只传路径,文件在方法中获取。哈哈 ,好东西分享一下。

import org.apache.commons.net.io.Util;

    public ActionForward down(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        String fullpath = request.getParameter("fullpath").trim(); // 文件的全路径
        String fileName =request.getParameter("filename").trim();
        InputStream in = null;
        try {
            in = new FileInputStream(fullpath);
            System.out.print(" read success");
            response.reset();// 必须重新设置,否则在第一次下载取消后,再下载会报response.getOutputStream()重复调用。
            response.setContentType("application/x-pn-realmedia");
            response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            System.out.print("copy start");
            Util.copyStream(in, response.getOutputStream());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            request.setAttribute("message", "文件不存在");
            return mapping.findForward("fail");
        } catch (IOException e) {
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
1 楼 lyo 2007-12-27  
需要 common-io吧,不知道性能如何
2 楼 cawyer 2007-12-27  
不要那个包包,其他的全是JAVA的包,性能没测试过,以前也能够smartupload总是乱吗,这个感觉还挺方便的