zoukankan      html  css  js  c++  java
  • 文件下载工具

    public class DownFileUtile {//str为文件的下载地址
        public static Logger logger = Logger.getLogger(DownFileUtile.class);
        public static void downLoad(String str, HttpServletRequest request, HttpServletResponse response){
            String extName = str.substring(str.lastIndexOf(".") + 1);
            String oldName = UUID.randomUUID().toString().replace("-","");
            String fileName =oldName+"."+extName;
            try {
                URL url = new URL(str);
                InputStream is = url.openStream();
                response.setContentType("application/doc");
                final String userAgent = request.getHeader("USER-AGENT");
                if(StringUtils.contains(userAgent, "MSIE")){//IE浏览器
                    fileName = URLEncoder.encode(fileName,"UTF-8");
                }else if(StringUtils.contains(userAgent, "Mozilla")){//google,火狐浏览器
                    fileName = new String(fileName.getBytes(), "ISO8859-1");
                }else{
                    fileName = URLEncoder.encode(fileName,"UTF-8");//其他浏览器
                }
                response.addHeader("Content-Disposition", "attachment;filename=" +fileName);//这里设置一下让浏览器弹出下载提示框,而不是直接在浏览器中打开
                ServletOutputStream os = response.getOutputStream();
                byte[] car = new byte[2048];
                int L;
                while((L = is.read(car)) != -1){
                    if (car.length!=0){
                        os.write(car, 0,L);
                    }
                }
                if(os!=null){
                    os.flush();
                    os.close();
                }
            } catch (Exception e) {
                logger.info("下载文件失败:"+e.getMessage());
            }
        }
    }
  • 相关阅读:
    Java的学习笔记(二)
    Java的学习笔记
    简单界面生成
    登录界面
    播放器
    java计划
    求和
    修改后的抽奖系统
    第十周作业
    JAVA第五次作业
  • 原文地址:https://www.cnblogs.com/appc/p/9104155.html
Copyright © 2011-2022 走看看