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

一分钟学习SpringMVC 下载

时间:2016-05-13 02:11:07      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:

SpirngMVC实现文件下载

        @RequestMapping("/login")
        public void get(HttpServletRequest request,HttpServletResponse response){

            response.setContentType("text/html;chaset=utf-8");
            try {
                request.setCharacterEncoding("utf-8");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            //定义输出流和输入流
            BufferedInputStream buffinput = null;
            BufferedOutputStream output   = null;
            String path = request.getSession().getServletContext().getRealPath("/")+"upload\\";
            String down = path+request.getParameter("fileName");

            try {
                File f =  new File(down);
                //获取文件长度
                long fileLength = new java.io.File(down).length();

                //输出文件
                buffinput = new BufferedInputStream(new FileInputStream(down));
                output   = new BufferedOutputStream(response.getOutputStream());
                 //设置头信息
                response.setContentType("application/x-msdownload");
                response.setHeader("content-length", String.valueOf(fileLength));
                response.setHeader("content-disposition", "attachment;filename="+new   String(request.getParameter("fileName").getBytes(),"ISO8859-1"));
                //创建输出数组
                byte[] bytelength = new byte[2048];
                int  byteread;
                //先进行读取 在输出
                while((byteread =buffinput.read(bytelength))!=-1 ){
                    output.write(bytelength,0,byteread);
                }
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{
                //关闭流
                try {
                    output.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            //注释返回值 因为我们把流关了 如果有返回值 会报 链接关闭异常
            //return "/MyJsp";
        }

注意 下载文件一定加扩展名称 不然会报找不到文件异常

一定不要有返回值 因为 转发用到了流操作,但是我们已经把它关闭了

一分钟学习SpringMVC 下载

标签:

原文地址:http://blog.csdn.net/x329357842/article/details/51347646

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