下载各类文件写法

下载文件写法:

  
  
  
  
  1. protected void doGet(HttpServletRequest req, HttpServletResponse resp)  
  2.             throws ServletException, IOException {  
  3.           
  4.         String fileId=req.getParameter("fileId");  
  5.         req.setCharacterEncoding("UTF-8");  
  6.         resp.setCharacterEncoding("UTF-8");  
  7.           
  8.         if(StringUtils.isNotEmpty(fileId)){  
  9.             FileAttach fileAttach=fileAttachService.get(new Long(fileId));  
  10.             String ext=fileAttach.getExt();  
  11.               
  12.             if(ext.toLowerCase().endsWith("zip")){  
  13.                 resp.setContentType("application/x-zip-compressed");  
  14.             }else if(ext.toLowerCase().endsWith("rar")){  
  15.                 resp.setContentType("application/octet-stream");  
  16.             }else if(ext.toLowerCase().endsWith("doc")){  
  17.                 resp.setContentType("application/msword");  
  18.             }else if(ext.toLowerCase().endsWith("xls") || ext.toLowerCase().endsWith("csv")){  
  19.                 resp.setContentType("application/ms-excel ");  
  20.  
  21.             }else if (ext.toLowerCase().endsWith("pdf")){  
  22.                 resp.setContentType("application/pdf");  
  23.             }else{  
  24.                 resp.setContentType("application/x-msdownload");  
  25.             }  
  26.  
  27.             ServletOutputStream out = null;  
  28.             try{  
  29.                   
  30.                 java.io.FileInputStream fileIn =new java.io.FileInputStream(getServletContext().getRealPath("/")+"/attachFiles/"+fileAttach.getFilePath());  
  31.  
  32.                 resp.setHeader("Content-Disposition""attachment;filename=" +URLEncoder.encode(fileAttach.getFileName(),"UTF-8"));   
  33.  
  34.                 out = resp.getOutputStream();  
  35.                   
  36.                 byte[] buff = new byte[1024];  
  37.                 int leng = fileIn.read(buff);  
  38.                 while(leng>0){  
  39.                     out.write(buff,0,leng);  
  40.                     leng = fileIn.read(buff);  
  41.                 }  
  42.             }catch(Exception ex){  
  43.                 ex.printStackTrace();  
  44.             }finally{  
  45.                 if(out!=null){  
  46.                     try {  
  47.                         out.flush();  
  48.                     } catch (IOException e) {  
  49.                         e.printStackTrace();  
  50.                     }  
  51.                     try {  
  52.                         out.close();  
  53.                     } catch (IOException e) {  
  54.                         e.printStackTrace();  
  55.                     }  
  56.                 }  
  57.  
  58.             }  
  59.               
  60.               
  61.         }  
  62.           
  63.     } 

 

本文出自 “互联网高端架构探索者” 博客,转载请与作者联系!

你可能感兴趣的:(java,职场,休闲)