2017-05-26 100 views
0

我對JSP/Servlets相當陌生,並試圖通過使用JSP文件中的以下代碼將文件/文件夾路徑和文件/文件夾名稱傳遞給servlet從本地目錄下載文件/文件夾使用servlet從URL下載文件或文件夾

<a href="<%=request.getContextPath()%>\download?filename=<filename>&filepath=http://192.168.0.101:8080<%=request.getContextPath()%>/<foldername>">Download Here</a> 

我想提高我的servlet下載的URL

e.g. 
If the Folder/File URL is passed to the servlet 

http://192.168.0.101:8080/folder 
http://192.168.0.101:8080/file.pdf 

下面通過任何類型的文件或文件夾的是我的servlet代碼:

import java.io.BufferedInputStream; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.IOException; 
import javax.servlet.*; 
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 { 
     String filename = request.getParameter("filename"); 
     String filepath = request.getParameter("filepath"); 
     BufferedInputStream buf=null; 
      ServletOutputStream myOut=null; 

     try{ 

     myOut = response.getOutputStream(); 
      File myfile = new File(filepath+filename); 
      response.setContentType("application/x-download"); 
      response.addHeader(
       "Content-Disposition","attachment; filename="+filename); 
      response.setContentLength((int) myfile.length()); 
      FileInputStream input = new FileInputStream(myfile); 
      buf = new BufferedInputStream(input); 
      int readBytes = 0; 
      while((readBytes = buf.read()) != -1) 
       myOut.write(readBytes); 
     } catch (IOException ioe){ 
       throw new ServletException(ioe.getMessage()); 
      } finally { 
       if (myOut != null) 
        myOut.close(); 
        if (buf != null) 
        buf.close(); 
      } 
    } 
} 

如果任何人都可以用上面的問題指向正確的方向,那對我來說真的很有幫助。

回答

0

無法從HTTP URL下載文件夾。你總是下載文件。

如果你想要下載一個完整的目錄,那麼你基本上必須遞歸地下載它裏面的所有文件和它的子目錄中的文件。或者您可以創建該文件夾的存檔並將其作爲下載提供。

對於以下部分代碼,您應該使用緩衝區,而不是在每次迭代中讀取一個字節。

int readBytes = 0; 
while((readBytes = buf.read()) != -1) 
    myOut.write(readBytes); 

隨着緩衝

byte[] buffer = new byte[4096];//4K buffer 
int readLen = 0; //Number of bytes read in last call to read, max is the buffer length 
while((readLen = buf.read(buffer)) != -1) { 
    myOut.write(buffer, 0, readLen); 
} 
  • 不要靠近myOut的OutputStream,它是由Servlet容器 處理。經驗法則是,如果你沒有打開它,不要關閉它。

  • filePath傳遞給Servlet可能會造成安全風險,您不知道用戶將嘗試下載哪些文件,可能是他會嘗試下載密碼哈希值。您應該使文件路徑相對於您想要提供下載的文件夾。然後,您將始終必須將該文件夾路徑預先添加到相對路徑,以便用戶只能從該文件夾下載文件。

  • 在您的下載頁面上,您可以列出(File.list())下載文件夾中的文件和文件夾,作爲超鏈接到您的文件夾,以便用戶不必鍵入文件名或路徑。