How to download File without using any third party API in JAVA

 

In previous posts we have seen how to upload a file into server in JAVA. In this post I’ll explain how to download file from server. There are various third party APIs available to perform this operations. But here I haven’t used any of them but the JAVA’s own API.

Project Structure:
Project Structure of File Download

Files:
1)web.xml
This is the deployment descriptor of the application where we have defined the servlet and given entry for the home page of the application.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">
	<display-name>FileDownloaderProject</display-name>

	<servlet>
		<servlet-name>downloader</servlet-name>
		<servlet-class>com.filedownloader.controller.DownloadServlet</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>downloader</servlet-name>
		<url-pattern>/downloaderServlet</url-pattern>
	</servlet-mapping>

	<welcome-file-list>
		<welcome-file>home.jsp</welcome-file>
	</welcome-file-list>
</web-app>

2)home.jsp
This is the home page of the application. Here we have a hyper link where the ‘href’ attribute is set to the “downloaderServlet” which is the URL pattern of the DownloadServlet. ${message} is used to display the failure message if any.

<%@ 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>File Downloader Example</title>
	</head>
	<body>
		<a href="./downloaderServlet">Click Here</a> to download the file.</br>
		${ERROR}
	</body>
</html>

3)DownloadServlet.java
This is the servlet class which handles the request for downloading the file. In doGet() method we are creating the File object by passing the absolute file path to File() constructor. Then we are checking whether file exists in the given location by using ‘file.exists()’. exists() method returns ‘true’ if file exists in given location else ‘false’. So when file is missing we are redirecting to the homepage with ‘file not found’ message.

If file exists then we are creating the InputStream for the file and getting the mime type of the file, which later we are setting to the response content type. Then file is read from the input stream and written to Servlet output stream and is flushed to perform the download operation.

We must set the ‘Content-Disposition’ as given in the code to download the file. We can set any file name to the downloading file there.

package com.filedownloader.controller;

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

import javax.servlet.RequestDispatcher;
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 DownloadServlet extends HttpServlet {
	
	@Override
	public void init() throws ServletException {
		System.out.println("Servlet initialized");
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		RequestDispatcher rd = request.getRequestDispatcher("/home.jsp");
		//creating the file object
		File file = new File("D:\\upload\\upload.txt");
		System.out.println("absolute path : "+file.getAbsolutePath());
		//checking file available in the directory or not
		if(!file.exists()){
			request.setAttribute("ERROR", "File is not available");
			rd.forward(request, response);
		}
		
		InputStream inputStream = new FileInputStream(file);
		//getting the file mime type
		String mimeType = getServletContext().getMimeType(file.getAbsolutePath());
		System.out.println("mimeType : "+mimeType);
		if(mimeType == null)
			mimeType = "application/octet-stream";	
		
		//preparing response object for file download
		response.setContentType(mimeType);
		response.setContentLength((int)file.length());
		response.setHeader("Content-Disposition", "attachment; filename=\"upload.txt\"");
		
		ServletOutputStream outputStream = response.getOutputStream();
		byte[] bytes = new byte[(int)file.length()];
		System.out.println("bytes.length : "+bytes.length);
		inputStream.read(bytes);
		outputStream.write(bytes);
		outputStream.flush();
		outputStream.close();
		inputStream.close();
		System.out.println("Download complete");
	}

}

Leave a comment

SUBSCRIBE TO NEWSLETTER

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Categories