码迷,mamicode.com
首页 > 编程语言 > 详细

Java下载文件

时间:2016-06-02 20:06:08      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:

public void downloadFile(){
        String filePath = request.getParameter("filepath");
        try {
            filePath = new String(filePath.getBytes("ISO-8859-1"),"UTF-8");
            String rootPath = request.getSession().getServletContext().getRealPath("/");
            File file = new File(rootPath+filePath);
            String downFileName = file.getName();
            
            InputStream fis = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(downFileName.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.close();
        } catch (Exception e) {
            log.errorLog("文件下载失败", e);
        }
    }

 

Java下载文件

标签:

原文地址:http://www.cnblogs.com/shangrongyiweng/p/5554171.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!