Java Web端程式實現檔案下載的方法分享_java

來源:互聯網
上載者:User

Web檔案下載有兩種,一種是檔案在網站目錄下,在瀏覽器中直接輸入檔案路徑即可下載,如http://www.xxx.com/file.zip。另外一種是檔案不在網站目錄下或者檔案是動態產生的(匯出報表或者匯出excel等),這種情況需要通過response的OutputStream實現檔案的下載。DownloadUtils是一個Java Web檔案下載工具類,提供多種靜態方法實現檔案下載。

package com.rhui.util;  import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URLEncoder;  import javax.servlet.http.HttpServletResponse;  import org.apache.commons.lang3.StringUtils;  /**  * 檔案下載類  */ public class DownloadUtils {   /**    * 檔案下載編碼    * 該編碼告訴瀏覽器檔案名稱的編碼方式,以防下載中文檔案名稱時有亂碼    */   private static String encoding = "utf-8";      /**    * 檔案下載    * @param response    * @param filePath 檔案在伺服器上的路徑,包含檔案名稱    */   public static void download(HttpServletResponse response, String filePath){     File file = new File(filePath.toString());     download(response, file, null, encoding);   }      /**    * 檔案下載    * @param response    * @param filePath 檔案在伺服器上的路徑,包括檔案名稱    * @param fileName 檔案下載到瀏覽器的名稱,如果不想讓瀏覽器下載的檔案名稱和伺服器上的檔案名稱一樣,請設定該參數    */   public static void download(HttpServletResponse response, String filePath, String fileName){     File file = new File(filePath.toString());     download(response, file, fileName, encoding);   }      /**    * 檔案下載    * @param response    * @param filePath 檔案在伺服器上的路徑,包括檔案名稱    * @param fileName 檔案下載到瀏覽器的名稱,如果不想讓瀏覽器下載的檔案名稱和伺服器上的檔案名稱一樣,請設定該參數    * @param encoding 檔案名稱編碼    */   public static void download(HttpServletResponse response, String filePath, String fileName, String encoding){     File file = new File(filePath.toString());     download(response, file, fileName, encoding);   }      /**    * 檔案下載    * @param response    * @param file 檔案    * @param fileName 檔案下載到瀏覽器的名稱,如果不想讓瀏覽器下載的檔案名稱和伺服器上的檔案名稱一樣,請設定該參數    */   public static void download(HttpServletResponse response, File file) {     download(response, file, null, encoding);   }      /**    * 檔案下載    * @param response    * @param file 檔案    * @param fileName 檔案下載到瀏覽器的名稱,如果不想讓瀏覽器下載的檔案名稱和伺服器上的檔案名稱一樣,請設定該參數    */   public static void download(HttpServletResponse response, File file, String fileName) {     download(response, file, fileName, encoding);   }      /**    * 檔案下載    * @param response    * @param file 檔案    * @param fileName 檔案下載到瀏覽器的名稱,如果不想讓瀏覽器下載的檔案名稱和伺服器上的檔案名稱一樣,請設定該參數    * @param encoding 檔案名稱編碼    */   public static void download(HttpServletResponse response, File file, String fileName, String encoding) {     if(file == null || !file.exists() || file.isDirectory()){       return;     }          // 如果不指定檔案下載到瀏覽器的名稱,則使用檔案的預設名稱     if (StringUtils.isBlank(fileName)) {       fileName = file.getName();     }      try {       InputStream is = new FileInputStream(file);       download(response, is, fileName, encoding);     } catch (IOException e) {       e.printStackTrace();     }   }      /**    * 檔案下載    * @param response    * @param is 檔案輸入資料流    * @param fileName 下載的檔案名稱    * @throws IOException    */   public static void download(HttpServletResponse response, InputStream is, String fileName){     download(response, is, fileName, encoding);   }      /**    * 檔案下載    * @param response    * @param is 檔案輸入資料流    * @param fileName 下載的檔案名稱    * @param encoding 編碼格式    */   public static void download(HttpServletResponse response, InputStream is, String fileName, String encoding){     if(is == null || StringUtils.isBlank(fileName)){       return;     }          BufferedInputStream bis = null;     OutputStream os = null;     BufferedOutputStream bos = null;          try{       bis = new BufferedInputStream(is);       os = response.getOutputStream();       bos = new BufferedOutputStream(os);       response.setContentType("application/octet-stream;charset=" + encoding);       response.setCharacterEncoding(encoding);       response.setHeader("Content-disposition", "attachment;filename="+ URLEncoder.encode(fileName, encoding));       byte[] buffer = new byte[1024];       int len = bis.read(buffer);       while(len != -1){         bos.write(buffer, 0, len);         len = bis.read(buffer);       }              bos.flush();     }catch(IOException e){       e.printStackTrace();     }finally{       if(bis != null){         try{           bis.close();         }catch(IOException e){}       }              if(is != null){         try{           is.close();         }catch(IOException e){}       }     }   }    public static String getEncoding() {     return encoding;   }    public static void setEncoding(String encoding) {     DownloadUtils.encoding = encoding;   } } 

如果檔案儲存在伺服器的非網站目錄下

String filePath = "c:\\file.zip"; DownloadUtils.download(response, filePath); 

如果檔案是輸入資料流

// is為檔案輸入資料流 // fileName為瀏覽器下載的檔案名稱 // encoding為檔案名稱編碼,預防檔案中有中文的時候產生亂碼 String fileName = "file.zip"; String encoding = "utf-8"; DownloadUtils.download(response, is, fileName, encoding); 

Servlet中檔案下載

package com.rhui.web.servlet;  import java.io.IOException;  import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;  import com.rhui.util.DownloadUtils;  @WebServlet("/download/servlet") public class DownloadServlet extends HttpServlet {   private static final long serialVersionUID = 1L;      protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {     String filePath = "c:\\file.zip";     DownloadUtils.download(response, filePath);   }  } 

PS:圖片下載(含防盜鏈功能)

package cn.itcast.day06.web.servlet; import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.URLEncoder; import javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; public class DownloadServlet extends HttpServlet {  public void doGet(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {  // 實現防盜鏈功能 // 獲得 referer 頭 用於說明來訪者來自哪裡 String referer = request.getHeader("referer"); if(referer==null || !referer.startsWith("http://localhost")) {  // 是盜鏈者  response.sendRedirect("/day06/index.jsp");  return ; }   // 解決response中文亂碼問題 response.setContentType("text/html;charset=utf-8"); // 設定訊息體的編碼   // 通過 http 協議 發送的http響應訊息頭 不能出現中文 中文必須要經過url編碼 String filename = URLEncoder.encode("美女.jpg", "utf-8");  // 通知瀏覽器以下載的方式讀取資源 response.setHeader("content-disposition", "attachment;filename="+filename);  // 讀取圖片資料 發給ie瀏覽器 String webPath = "/download/美女.jpg"; // 相當於當前web應用的path  ServletContext servletContext = super.getServletContext();  InputStream in = servletContext.getResourceAsStream(webPath);   OutputStream out = response.getOutputStream();   int len; byte[] buffer = new byte[1024]; while((len=in.read(buffer))!=-1)  out.write(buffer, 0, len);  }  public void doPost(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException { doGet(request, response); } }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.