java流文件下载

@ApiOperation("文件下载")
    @GetMapping("/downLoad")
    public Result downLoad(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "fileName",required = false) String fileName, @RequestParam(value = "downLoadPath",required = false) String downLoadPath) throws  Exception{
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            //如果不存在乱码的情况可以忽略,由于请求参数文件名为中文,到后台会乱码,考虑操作系统和客户端浏览器默认编码
            //判断服务器操作系统,本地开发使用windows
            String os = System.getProperty("os.name");
            if(os.toLowerCase().indexOf("windows") != -1){
                fileName = new String(fileName.getBytes("GBK"), "ISO-8859-1");
            }else{
                //判断浏览器
                String userAgent = request.getHeader("User-Agent").toLowerCase();
                if(userAgent.indexOf("msie") > 0){
                    fileName = URLEncoder.encode(fileName, "ISO-8859-1");
                }
            }
            //响应二进制流
            response.setContentType("application/octet-stream");
            //清除response中的缓存
            response.reset();
            //根据网络文件地址创建URL
            URL url = new URL(downLoadPath);
            //获取此路径的连接
            URLConnection conn = url.openConnection();
            Long fileLength = conn.getContentLengthLong();//获取文件大小
            //设置reponse响应头,真实文件名重命名,就是在这里设置,设置编码
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + fileName);
            response.setHeader("Content-Length", String.valueOf(fileLength));

            bis = new BufferedInputStream(conn.getInputStream());//构造读取流
            bos = new BufferedOutputStream(response.getOutputStream());//构造输出流
            byte[] buff = new byte[1024];
            int bytesRead;
            //每次读取缓存大小的流,写到输出流
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
            //将所有的读取的流返回给客户端
            response.flushBuffer();
        } catch (IOException e) {
            return  ResultData.fail("文件下载失败!");
        }finally{
            try{
                if(null != bis){
                    bis.close();
                }
                if(null != bos){
                    bos.close();
                }
            }catch(IOException e){
                return ResultData.fail("文件流关闭失败!");
            }
        }
        return null;
    }

 

你可能感兴趣的:(java)