首页 > 其他 > 详细

Servlet下载文件

时间:2015-09-02 20:34:08      阅读:294      评论:0      收藏:0      [点我收藏+]

1.获取项目根目录:

@Override
    public void init() throws ServletException {
        // 获取项目在文件系统中的根目录
        string = getServletContext().getRealPath(File.separator);
    }

init()方法在整个Servlet生命周期内只会被加载一次,用于数据的初始化。

 

2.下载文件代码:

@Override
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        //配置文件路径
        String filePath = string + "download" + File.separator + "18612.jpg";
        //通过UUID获取宇宙唯一文件名,并将其中‘-’连接符去掉
        String fileName=UUID.randomUUID().toString().replace("-", "");
        // 设置下载文件名
        response.setHeader("content-disposition",
                "attachment;filename="+fileName+".jpg");
        // 获取输出流
        ServletOutputStream outputStream = response.getOutputStream();
        // 把文件写入tomcat
        InputStream inputStream = new FileInputStream(new File(filePath));
        byte[] b = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(b)) != -1) {
            //输出到浏览器
            outputStream.write(b, 0, len);
        }
        if (inputStream!=null) {
            inputStream.close();
        }
        if (outputStream!=null) {
            outputStream.close();
        }
    }

 

Servlet下载文件

原文:http://www.cnblogs.com/mada0/p/4779338.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!