File Download using Java Servlet – server to client with example

The following code illustrates how to download a file from a server to client. It will open a dialog open or save.

Steps :

1. Get the file name

2. Read the file contents and put it in a byte array.

3. Set the response setContentType to  type of the file (eg. msword, xls , octet-stream)

4. Set the response SetHeader to attachment & filename which will prompt the file to download.

5. get Response output stream

6. Write the byte array data into the response output stream.

The complete servlet code is given below

FileDownLoad.java

 

package net.javaonline.servlet.fileupload;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class GetDetails
 */
@WebServlet("/readDoc")
public class FileDownLoad extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FileDownLoad() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String docId = request.getParameter("docId")!=null?request.getParameter("docId"):"NA";
		
		ServletOutputStream sos;
        
	     String fileName="C:\\temp\\"+docId+".pdf";  //.docx or .txt

	     System.out.println(fileName);

	     File f = new File(fileName);

	     FileInputStream istr = new FileInputStream(f);

	     BufferedInputStream bstr = new BufferedInputStream( istr );

	     int size = (int) f.length(); // get the file size (in bytes)

	     byte[] data = new byte[size];

	     bstr.read( data, 0, size ); // read into byte array

	     bstr.close();

	     response.setContentType("application/octet-stream");

	     response.setHeader("Content-Disposition","attachment; filename=\"" + fileName + "\"");

	     sos = response.getOutputStream();

	     sos.write(data);

	     sos.flush();

	     sos.close();
	     
	  
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}

The above code accepts document id and the equivalent file name is read from the path c:/temp and written to response output stream. Please ensure that the physical file corresponding to the document id (ie. document1.pdf or document1.docx, document2.pdf…) is placed in the folder c:\temp

The below JSP is to accept  document id and submits  to the servlet

documentRead.jsp

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>

<html>
   <head>
        <title>Document Download</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
<body>
<form  method="get" action="readDoc">
	<table>
	<tr>
	<td>Enter Document Id</td>
	<td>
	
	<select name="docId">
		  <option value="document1">Document1</option>
		  <option value="document2">Document2</option>
		  <option value="document3">Document3</option>
   </select>
	</td>
	</tr>
	<tr>
	<td colspan="2">	<input  type="submit"  value="Get Document" /></td></tr>
	</table>

</form>

</body>
</html>

Run the above project by calling

http://localhost:8080//documentRead.jsp

file download

Clicking on the Get Document button, downloads the document1.pdf

 

You may also like