File Uploading and Downloading in JSP

File Uploading and Downloading in JSP with Examples

In this article, I am going to discuss File Uploading and Downloading in JSP with Examples. Please read our previous article where we discussed Cookies Handling in JSP with Examples. At the end of this article, you will understand the following pointers.

  1. The need for JSP File Uploading & Downloading
  2. Uploading a file to the server using JSP
  3. Understanding MultipartRequest class and its methods
  4. JSP File Upload
  5. Example: Using Action
  6. Example: Using JSP operations
  7. Downloading File
  8. Example of File Downloading
The Need for File Uploading and Downloading in JSP

File Input and Output are very important operations in JSP where we can easily read and write a file using JSP. The JSP file can be used with HTML using different tags to permit the manipulators to upload files to the respective server which is not always the same. It may be a text file, image file, video file, and also some other formats as per our requirements.

Uploading a file to the server using JSP

There are multiple ways to upload the file to the server. MultipartRequest class is one of the ways to upload files to the server. To use MultipartRequest class we need to have a cos.jar file. Below are the important points to be noted:

  1. Form method attribute should be set to POST.
  2. Form encrypt attribute should be set to multipart/form-data.
  3. Form action attribute should be set to JSP file which is handling file uploading to the backend server.
  4. Use <input …/> tag once to upload a single file.
  5. To upload multiple files, use multiple input tags.
Constructors of MultipartRequest class
  1. MultipartRequest(HttpServletRequest request, String saveDirectory): It is used to uploads the file into 1MB.
  2. MultipartRequest(HttpServletRequest request, String saveDirectory, int maxPostSize): It is used to upload the file up to a specified post size.
  3. MultipartRequest(HttpServletRequest request, String saveDirectory, int maxPostSize, String encoding): It is used to upload the file up to a specified post size with given encoding.

Uploading File Example

Using Action

In this example, we are uploading a file using an IO object. In Action.jsp file, we are creating a form that will upload the file to the server, and action will be passed to ActionUpload.jsp file. In ActionUpload.jsp file, we are giving the file path to a particular path. Here, we are also checking whether the content type is multipart/form-data. If it is then the content is read and is of file type.

Action.jsp
<%@ 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</title>
</head>
<body>
 <a>File Upload:</a> <br/><br/>	
 <form action="ActionUpload.jsp" method="post"
  enctype="multipart/form-data">
  Select file: <input type="file" name="file" size="50" /> <br /><br/> <input
   type="submit" value="Upload File" />
 </form>
</body>
</html>
ActionUpload.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<%@ page import="java.io.*,java.util.*, javax.servlet.*"%>
<%@ page import="javax.servlet.http.*"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="org.apache.commons.fileupload.disk.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.*"%>
<%@ page import="org.apache.commons.io.output.*"%>
<!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 Upload</title>
</head>
<body>
 <%
  File file;
 int maxFileSize = 5000 * 1024;
 int maxMemSize = 5000 * 1024;
 String filePath = "G:/data";

 String contentType = request.getContentType();
 if ((contentType.indexOf("multipart/form-data") >= 0)) {

  DiskFileItemFactory factory = new DiskFileItemFactory();
  factory.setSizeThreshold(maxMemSize);
  factory.setRepository(new File("c:\\test"));
  ServletFileUpload upload = new ServletFileUpload(factory);
  upload.setSizeMax(maxFileSize);
  try {
   List fileItems = upload.parseRequest(request);
   Iterator i = fileItems.iterator();
   
   while (i.hasNext()) {
  FileItem fi = (FileItem) i.next();
  if (!fi.isFormField()) {
   String fieldName = fi.getFieldName();
   String fileName = fi.getName();
   boolean isInMemory = fi.isInMemory();
   long sizeInBytes = fi.getSize();
   file = new File(filePath + "yourFileName");
   fi.write(file);
   
  }
   }
   
  } catch (Exception ex) {
   System.out.println(ex);
  }
 } 
 %>
</body>
</html>

Output: Run your code to get the following output.

File Uploading and Downloading in JSP with Examples

Upload file using choose file button option and upload file button will upload the file in the specified path.

File Uploading and Downloading in JSP with Examples

Using JSP Operations

In this example, we will upload files using JSP Operations. We will take the form “uploading.jsp” with the “Upload” button, click on the upload button to upload the file. We create a “upload.java” file which will be called as we are passing the POST method in JSP and it will request and the response objects as its parameters. Here we will iterate the files by checking how many items are present in multiparts objects which is a list object and save it to the g:/data folder with the file name which has been provided. We are writing the file using the write method. In the “result.jsp” file we are getting the attribute from the request object with value message into a string object and we are printing that message.

uploading.jsp
<%@ 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>Uploading File</title>
</head>
<body>
 File:
 <br />
 <form action="upload.java" method="post" enctype="multipart/form-data">
  <input type="file" name="file" size="50" /> <br /> <input
   type="submit" value="Upload" />
 </form>
</body>
</html>
upload.java
package Action;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class upload extends HttpServlet {
 private static final long serialVersionUID = 1L;

 public upload() {
  super();
  // TODO Auto-generated constructor stub
 }

 protected void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  if (ServletFileUpload.isMultipartContent(request)) {
   try {
    List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
    for (FileItem item : multiparts) {
     if (!item.isFormField()) {
      String name = new File(item.getName()).getName();
      item.write(new File("c:/test" + File.separator + name));
     }
    }
    // File uploaded successfully
    request.setAttribute("message", "File Uploaded Successfully");
   } catch (Exception ex) {
    request.setAttribute("message", "File Upload Failed due to " + ex);
   }
  } else {

   request.setAttribute("message", "No File found");
  }
  request.getRequestDispatcher("/result.jsp").forward(request, response);

 }

}
result.jsp
<%@ 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> Result</title>
</head>
<body>
 <%
  String msg = (String) request.getAttribute("message");
 out.println(msg);
 %>
</body>
</html>
Output

Run your code to get the following output:

File Uploading in JSP with Examples

Choose your file and click on the “Upload” button. You will get the following output once your file will be successfully uploaded.

File Uploading in JSP with Examples

You can also check your g:/data folder. You can see the file has been uploaded.

File Uploading in JSP with Examples

Downloading File in JSP

In this example, we are downloading a file from a directory by clicking on the link in the “input.html” file. We have given a link to download a file from folder g:/data using the “download.jsp” file. In this, we are setting the content type using the response object and creating FileInputstream in which we will add path and file. Here we are using a while loop which will run till the file is read, hence we have given the condition as !=-1 where we are writing using the out object.

index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
 <a href="download.jsp">download the jsp file</a>
</body>
</html>
download.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
 <%
  String filename = "new.txt";
 String filepath = "G:\\data";
 response.setContentType("APPLICATION/OCTET-STREAM");
 response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");

 java.io.FileInputStream fileInputStream = new java.io.FileInputStream(filepath + filename);

 int i;
 while ((i = fileInputStream.read()) != -1) {
  out.write(i);
 }
 fileInputStream.close();
 %>
</body>
</html>
Output

Run index.html file to get the following output.

File Downloading in JSP with Examples

Then click on the link and check your downloads folder.

File Downloading in JSP with Examples

In the next article, I am going to discuss How to Hande Dates in JSP. Here, in this article, I try to explain JSP File Uploading and Downloading with Examples. I hope you enjoy this JSP File Uploading and Downloading with Examples article.

Leave a Reply

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