/** * 下載遠程服務器文件 */ @RequestMapping("/download_file") public void downloadFile(HttpServletRequest request,HttpServletResponse response){ OutputStream os = null; ReadableByteChannel rbc = null; try{//獲取文件名 String fileExtName = "aa.jpg"; //根據條件得到文件路徑 String fileurl = "http://d.hiphotos.baidu.com/zhidao/pic/item/0e2442a7d933c895623a9a8fd11373f0830200f9.jpg"; if(!fileExtName.equals("")){ os = response.getOutputStream(); log.info("===========文件路徑==========="+fileurl); //獲取遠程文件 URL website = new URL(ConfigInfo.getString("file_server_path")+fileurl); //獲取數據通道 rbc = Channels.newChannel(website.openStream()); //獲得瀏覽器代理信息 final String userAgent = request.getHeader("USER-AGENT"); //判斷瀏覽器代理並分別設置響應給瀏覽器的編碼格式 String finalFileName = null; if(StringUtils.contains(userAgent, "MSIE")||StringUtils.contains(userAgent,"Trident")){//IE瀏覽器 finalFileName = URLEncoder.encode(fileExtName,"UTF8"); System.out.println("IE瀏覽器"); }else if(StringUtils.contains(userAgent, "Mozilla")){//google,火狐瀏覽器 finalFileName = new String(fileExtName.getBytes(), "ISO8859-1"); }else{ finalFileName = URLEncoder.encode(fileExtName,"UTF8");//其他瀏覽器 } //設置HTTP響應頭 response.reset();//重置 響應頭 response.setContentType("application/x-download");//告知瀏覽器下載文件,而不是直接打開,瀏覽器默認為打開 response.addHeader("Content-Disposition" ,"attachment;filename=\"" +finalFileName+ "\"");//下載文件的名稱 //讀取數據 ByteBuffer bb = ByteBuffer.allocate(1024); int index = -1; // 循環取出流中的數據 while ((index = rbc.read(bb)) > 0){ if (index <= 0) { break; } bb.position(0); byte[] b = new byte[index]; bb.get(b); //將數據輸出 os.write(b, 0, index); bb.clear();//緩沖區不會被自動覆蓋,需要主動調用該方法 } }else{ log.info("找不到該文件!"); } }else{ log.info("參數異常!"); } }catch(MalformedURLException e){ e.printStackTrace(); log.debug("獲取文件錯誤!", e); } catch (IOException e) { e.printStackTrace(); log.debug("下載異常!", e); }finally{ try { if(rbc != null){ rbc.close(); } if(os != null){ os.close(); } } catch (IOException e) { e.printStackTrace(); log.debug("流關閉異常!", e); } } }
