Download File From Server Using Servlet Example

Here you will get example to download file from server using servlet. The file can be of any type like image, pdf, video, music, etc.

How it works?

  • First set the content type to application/octet-stream.
  • Now set the Content-Disposition header to attachment;filename=fileLocation.
  • Read file from the source location using FileInputStream and write to ServletOutputStream to send as response.

Also Read: Upload File to Server Using Servlet Example

Download File From Server Using Servlet Example

WebContent/index.html

This page contains a download link.

<html>
    <head>
        <title>File Download Example</title>
    </head>
    
    <body>
        <a href = "download">Click Here To Download</a>
    </body>
</html>

src/com/DownloadServlet.java

This is the servlet responsible for downloading the required file.

package com;

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;

@WebServlet("/download")
public class DownloadServlet extends HttpServlet{
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String fileLocation = "E:\\video.mp4";	//change the path according to you
		File file = new File(fileLocation);
		FileInputStream fis = new FileInputStream(file);
		ServletOutputStream sos = resp.getOutputStream();
		
		resp.setContentType("application/octet-stream");
		resp.setHeader("Content-Disposition", "attachment;filename=" + fileLocation);
				
		byte[] buffer = new byte[4096];

		while((fis.read(buffer, 0, 4096)) != -1){
			sos.write(buffer, 0, 4096);
		}
		
		fis.close();
	}	
}

Download File From Server Using Servlet Example

Comment below if you have doubts or found any mistake in above servlet download file example.

Leave a Comment

Your email address will not be published. Required fields are marked *