Servlet download files sample application
In this example we will create Servlet download files sample application where client can download files from server:
- Project structure:
- index.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <h3> Click download sample file: <a href="DownloadServlet">JavaHonkDownload.txt</a> </h3> </body> </html>
- DownloadServlet.java:
package com.javahonk.servlet; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.tomcat.util.http.fileupload.IOUtils; /** * Servlet implementation class DownloadServlet */ public class DownloadServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public DownloadServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext context = request.getServletContext(); File downloadFile = new File("C:/JavaHonk/JavaHonkDownload.txt"); FileInputStream inputStream = null; OutputStream outStream = null; try { inputStream = new FileInputStream(downloadFile); response.setContentLength((int) downloadFile.length()); response.setContentType(context.getMimeType("C:/JavaHonk/JavaHonkDownload.txt")); // response header String headerKey = "Content-Disposition"; String headerValue = String.format("attachment; filename=\"%s\"",downloadFile.getName()); response.setHeader(headerKey, headerValue); // Write response outStream = response.getOutputStream(); IOUtils.copy(inputStream, outStream); } catch (Exception e) { e.printStackTrace(); } finally { try { if (null != inputStream) inputStream.close(); if (null != inputStream) outStream.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } }
- Configure tomcat server to eclipse using this tutorial. To run –> Right click project –> Run As –> Run on Server. You will see below page with download link:
- File download pop up:
For more information please read servlet tutorial here.
Download Project: DownloadFileServlet