我對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();
}
}
}
如果任何人都可以用上面的問題指向正確的方向,那對我來說真的很有幫助。