一分钟学习SpringMVC 下载

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

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值