Implementing File Downloads Using Servlets
Problem Statement
This question explores how to implement a servlet to facilitate file downloads from a server. The servlet receives a file name as a parameter in a GET request and aims to return that file to the user's browser for download.
Solution
To implement a simple file download servlet, consider the following steps:
Configure Servlet in web.xml:
Add the servlet definition and mapping to the web.xml file to make the servlet available through the web server.
Implement DownloadServlet:
Create a servlet class, extending the HttpServlet class, to handle the file download requests. In the doGet method:
Example Code
Below is a sample implementation of the DownloadServlet:
public class DownloadServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String fileName = request.getParameter("id"); response.setContentType("application/pdf"); response.setHeader("Content-disposition", "attachment; filename=yourcustomfilename.pdf"); File my_file = new File(fileName); OutputStream out = response.getOutputStream(); FileInputStream in = new FileInputStream(my_file); byte[] buffer = new byte[4096]; int length; while ((length = in.read(buffer)) > 0) { out.write(buffer, 0, length); } out.flush(); } }
The above is the detailed content of How to Implement a Servlet for File Downloads?. For more information, please follow other related articles on the PHP Chinese website!