JAVA文件下载代码(兼容safari的乱码问题)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/dujianxiong/article/details/80844652


public void downFile(HttpServletResponse response, HttpServletRequest httpServletRequest) {
        response.setContentType("application/octet-stream");

        String path = httpServletRequest.getParameter("file");
        String fileName=path.substring(path.lastIndexOf("/")+1);
        try {
            //bugfix: fileName包含中文导致fileNotFound
            path = path.substring(0,path.lastIndexOf("/")+1) + URLEncoder.encode(fileName, "UTF-8");

            String userAgent = httpServletRequest.getHeader("User-Agent").toLowerCase();
            //chrome头也包含safari,需要排除chrome
            if(userAgent.contains("safari") && !userAgent.contains("chrome")){
                //处理safari的乱码问题
                byte[] bytesName = fileName.getBytes("UTF-8");
                fileName = new String(bytesName, "ISO-8859-1");
                response.setHeader("content-disposition", "attachment;fileName="+ fileName);
            }else{
                response.setHeader("content-disposition", "attachment;fileName="+ URLEncoder.encode(fileName, "UTF-8"));
            }
//            //文件名外的双引号处理firefox的空格截断问题
//            response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", fileName));

            OutputStream output = response.getOutputStream();
            URL url = new URL(path);
            //输入缓冲流
            BufferedInputStream bis=new BufferedInputStream(url.openStream());
            //输出缓冲流
            BufferedOutputStream bos=new BufferedOutputStream(output);
            //缓冲字节数
            byte[] data =new byte[4096];
            int size=0;
            size=bis.read(data);
            while (size!=-1){
                bos.write(data,0,size);
                size=bis.read(data);
            }
            bis.close();
            bos.flush();//清空输出缓冲流
            bos.close();
        } catch (Exception e) {
            logger.error("downFile error",e);
        }
    }

猜你喜欢

转载自blog.csdn.net/dujianxiong/article/details/80844652