How to Download File using Servlet

Consider that I have file containing project information available into server and I want to download that file. Using webservices you can also achieve same but Here, I am going to discuss "Download File using Servlet"

Steps to be Performed to Download File using Servlet :
  1. Create Servlet File which will download file available in server
  2. Add Servlet entry into Web.xml or annotate with @WebServlet 
Define servlet into Web.xml (If you are not using Annotation @WebServlet):


    DownloadFile
    com.anuj.core.DownloadFile
  
  
    DownloadFile
    /Download
  

Download File using Servlet Sample Example :

package com.anuj.core;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class DownloadServlet
 */
@WebServlet("/Download")
public class DownloadFile extends HttpServlet {
 private static final long serialVersionUID = 1L;
       
    /**
  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 
  response.setContentType("text/plain");
  response.setHeader("Content-Disposition","attachment;filename=downloadname.txt");
  
  ServletContext context = getServletContext();
  InputStream inputStream = context.getResourceAsStream("/ProjectInformation.txt");
  
  byte[] bytes = new byte[1024];
  int read=0;
  OutputStream outputStream = response.getOutputStream();
  
  while((read=inputStream.read(bytes))!= -1){
   outputStream.write(bytes,0,read);
  }
  
  outputStream.flush();
  outputStream.close();
 }
}

Please refer to Internet Media Type for more details if you require other mime types

No comments:

Post a Comment