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()); } } }
原文地址:https://www.cnblogs.com/appc/p/9104155.html
时间: 2024-10-29 14:00:34