How to download file in JSP?

In the previous article, we have seen the Uploading of Files using JSP How to upload file in JSP?. In this article, we will discuss the Downloading of File, images from a server in JSP.

As we know, Uploading and Downloading Features are very important in Web Application. For that purpose, we will discuss how to download a file in JSP in the following example.

Example of File Downloading in JSP

In this application, we will be creating two files

  • index.jsp
  • downloadFile.jsp

We will create a project structure as shown below using Eclipse IDECreate an index.jsp file with a hyperlink Download

<%@ 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 Download</title>
</head>
<body>
Click to Download <a href="downloadFile.jsp">Download</a>
</body>
</html>

Create a downloadFile.jsp file

  • The First step is to locate the File path.
  • Set a response as APPLICATION/OCTET-STREAM because APPLICATION/OCTET-STREAM stands for binary data(it is always good if we specify the actual file type).
  • Set Header as Content-Disposition.The content-disposition filed is added to specify the presentation style.
response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
  • an attachment content-disposition, in this case, it is not displayed automatically and requires some form of action from the user to open it(in this case we say don’t open the file instead just save it ).
<%@page import="java.io.FileInputStream"%>
<%@ 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>Insert title here</title>
</head>
<body>
  <%
response.setContentType("text/html");
String filename="img.jpg";
String filepath="E:\\java\\";
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
FileInputStream fileInputStream=new FileInputStream(filepath+filename);
int i;
while((i=fileInputStream.read())!=-1)
{
  out.write(i);
}
fileInputStream.close();
out.close();
%>
</body>
</html>

Now Run The program on the Server form index.jsp  file

As soon as you click on Save It will download the file from the local host machine path which you have provided in the program and it will ask you a location to save.

Thus, this is How we download a file, image, or any document in JSP.