Home >Java >javaTutorial >How to Implement a File Download Servlet in Java?
Implementing File Download Servlet
Implementing a file download servlet allows users to retrieve files from a web application.
How to Implement File Download:
To enable file download, we can create a servlet that serves as the download endpoint and map it to a specific URL in web.xml.
Example Servlet:
DownloadServlet.java
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class DownloadServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the file ID from the request String id = request.getParameter("id"); // Fetch file metadata from the database String fileName = ""; String fileType = ""; // Set the response content type based on file type response.setContentType(fileType); // Set the content disposition header to prompt download response.setHeader("Content-disposition", "attachment; filename=yourcustomfilename.pdf"); // Create a File object using the file path File file = new File(fileName); // Stream the file to the client InputStream in = new FileInputStream(file); OutputStream out = response.getOutputStream(); // Copy file content in chunks byte[] buffer = new byte[4096]; int length = 0; while ((length = in.read(buffer)) > 0) { out.write(buffer, 0, length); } in.close(); out.flush(); } }
In the servlet's doGet method, we:
Mapping in web.xml:
<servlet> <servlet-name>DownloadServlet</servlet-name> <servlet-class>com.myapp.servlet.DownloadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>DownloadServlet</servlet-name> <url-pattern>/download</url-pattern> </servlet-mapping>
This setup allows users to download files by sending a GET request to /download?id=
The above is the detailed content of How to Implement a File Download Servlet in Java?. For more information, please follow other related articles on the PHP Chinese website!