• 文件下载工具


    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());
            }
        }
    }
  • 相关阅读:
    C语言的特点与缺点
    C语言的特点与缺点
    HDU1234 开门人和关门人
    HDU1234 开门人和关门人
    B00014 C++实现的AC自动机
    B00014 C++实现的AC自动机
    HDU4716 A Computer Graphics Problem
    HDU4716 A Computer Graphics Problem
    I00029 C语言程序-打印九九乘法表
    I00029 C语言程序-打印九九乘法表
  • 原文地址:https://www.cnblogs.com/appc/p/9104155.html
Copyright © 2020-2023  润新知