java文件下载案例代码

java | 2019-09-13 10:02:39

无论是servlet还是spring controller,都用输出流的方式实现文件下载,而且请注意字符格式的设置,否则会乱码


String path=request.getParameter("path");//从页面获取要下载的文件的相对路径
            if(!"".equals(path)){
                path=new String(path.getBytes("ISO-8859-1"),"UTF-8");
                File file=new File(getServletContext().getRealPath("/")+path);//构造要下载的文件    
                if(file.exists()){
                    InputStream ins=new FileInputStream(getServletContext().getRealPath("/")+path);//构造一个读取文件的IO流对象
                    BufferedInputStream bins=new BufferedInputStream(ins);//放到缓冲流里面
                    OutputStream outs=response.getOutputStream();//获取文件输出IO流
                    BufferedOutputStream bouts=new BufferedOutputStream(outs);
                    response.setContentType("application/x-download");//设置response内容的类型
                    response.setHeader("Content-disposition","attachment;filename="+ URLEncoder.encode(path, "UTF-8"));//设置头部信息
                    int bytesRead = 0;
                    byte[] buffer = new byte[8192];
                    //开始向网络传输文件流
                    while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {
                        bouts.write(buffer, 0, bytesRead);
                    }
                    bouts.flush();//这里一定要调用flush()方法
                    ins.close();
                    bins.close();
                    outs.close();
                    bouts.close();
                }else{
                    System.out.println("下载的文件不存在");
                }
            }else{
                System.out.println("下载文件时参数错误");
            }



登录后即可回复 登录 | 注册
    
关注编程学问公众号