Servlet File Download

Servlet File Download


Posted in : Java Posted on : May 24, 2012 at 6:49 PM Comments : [ 0 ]

In this tutorial you will learn about files in servlet using servlet

Servlet File Download

Follow the Steps to download file from servlet

  • Get the path of the file and create the FileInputStream object as
    	FileInputStream fileToDownload = new FileInputStream(filePath);
    	
  • Then create the ServletOutputStream from the response as
    	ServletOutputStream output = response.getOutputStream();
    	
  • Set the Content (MIME) type, response header and content length as
    	response.setContentType("application/zip");
    	response.setHeader("Content-Disposition", "attachment; filename="+ fileName);
    	response.setContentLength(fileToDownload.available());
    	
  • Now create the byte array and read the data from the InputStream and write it to the OutputStream
    	int readBytes = 0;
    	byte[] buffer = new byte[10000];
    	while ((readBytes = fileToDownload.read(buffer, 0, 10000)) != -1) {
    		output.write(readBytes);
    	}
    	

The complete Servlet class is given below

ServletFileDownload.java

	package devmanuals.servlet;
	
	import java.io.FileInputStream;
	import java.io.IOException;
	
	import javax.servlet.ServletException;
	import javax.servlet.ServletOutputStream;
	import javax.servlet.http.HttpServlet;
	import javax.servlet.http.HttpServletRequest;
	import javax.servlet.http.HttpServletResponse;
	
	public class ServletFileDownload extends HttpServlet {
	
		public void doGet(HttpServletRequest request, HttpServletResponse response)
				throws ServletException, IOException {
			String filePath ="C:\\testComboBox.zip";
			String fileName ="test.zip";
			FileInputStream fileToDownload = new FileInputStream(filePath);
			ServletOutputStream output = response.getOutputStream();
			response.setContentType("application/zip");
			response.setHeader("Content-Disposition", "attachment; filename="+ fileName);
			response.setContentLength(fileToDownload.available());
			
			int readBytes = 0;
			byte[] buffer = new byte[10000];
			while ((readBytes = fileToDownload.read(buffer, 0, 10000)) != -1) {
				output.write(readBytes);
			}
			
			output.close();
			fileToDownload.close();
			fileToDownload.close();
		}
	}
	

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics