• Home
  • Testing
  • SAP
  • Web
  • Must Learn!
  • Big Data
  • Live Projects
  • Blog
  • Job

In this example, we are going to learn about uploading and downloading of a file through JSP.

File Input output are very important operations. Here we are going to read and write a file using JSP.

JSP File Upload

  • We can upload any files using JSP.
  • It can be a text file, binary file, image file or any other document.
  • Here in case of file uploading, only POST method will be used and not the GET method.
  • Enctype attribute should be set to multipart/form-data.

Example: Using Action

In this example, we are uploading a file using IO object

Action_file.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>Guru File</title>
</head>
<body>
<a>Guru File Upload:</a>
Select file: <br />
<form action="action_file_upload.jsp" method="post"
                        enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>

Action_file_upload.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>Guru File Upload</title>
</head>
<body>
<%
   File file ;
   int maxFileSize = 5000 * 1024;
   int maxMemSize = 5000 * 1024;
   String filePath = "E:/guru99/data";

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

      DiskFileItemFactory factory = new DiskFileItemFactory();
      factory.setSizeThreshold(maxMemSize);
      factory.setRepository(new File("c:\\temp"));
      ServletFileUpload upload = new ServletFileUpload(factory);
      upload.setSizeMax( maxFileSize );
      try{ 
         List fileItems = upload.parseRequest(request);
         Iterator i = fileItems.iterator();
         out.println("<html>");
         out.println("<body>");
         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 ) ;
                out.println("Uploaded Filename: " + filePath + fileName + "<br>");
            }
         }
         out.println("</body>");
         out.println("</html>");
      }catch(Exception ex) {
         System.out.println(ex);
      }
   }else{
      out.println("<html>");
      out.println("<body>");
      out.println("<p>No file uploaded</p>"); 
      out.println("</body>");
      out.println("</html>");
   }
%>
</body>
</html>

Explanation of the code:

Action_file.jsp

Code Line 12-18: Here we are creating form with file field, which will upload file to the server and action will be passed to action_file_upload.jsp

Action_file_upload.jsp

Code Line 20: Here we are giving the file path to a particular path

Code Line 23-38: Here we check whether the content type is multipart/form-data. If that is the case, then the content is of file type, and it is read. After file being read, it is written into the temporary file and then the temporary file gets converted to the main file.

When you execute the above code, you get the following output

JSP Action - File Upload, JSP Filter, Client Request, Server Response, Cookies Handling, Date Handling

Output:

We are uploading file using choose file button option and upload file button will upload the file to the server to the path which is provided.

Example: Using JSP operations

In this example, we are going to upload a file using JSP operations.

We will take a form which will have "upload" button and when you click on upload button then the file will be uploaded.

Uploading_1.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>Guru Uploading File</title>
</head>
<body>
File: <br />
<form action="guru_upload" method="post"
                        enctype="multipart/form-data">
<input type="file" name="guru_file" size="50" />
<br />
<input type="submit" value="Upload" />
</form>
</body>
</html>

Explanation of the code:

Code Line 11-12: Here we are taking a form which has action on servlet guru_upload which will pass through a method POST. Also, here we enctype i.e. attribute which specifies how form data should be encoded and sent to server and it is only used with POST method. Here we are setting as multipart/form-data which is for the file(as data will be large).

Code Line 13: Here we are specifying guru_file element with type file and giving size as 50.

Code Line 15: This is a submit type button with name "Upload" on it through which action servlet will be called and request will processed into that and file will be read and write into the servlet.

Guru_upload.java

package demotest;

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 guru_upload extends HttpServlet {
	private static final long serialVersionUID = 1L;
 
    public guru_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:/guru/upload" + File.separator + name));
		                    }
		                }
		               //File uploaded successfully
		               request.setAttribute("gurumessage", "File Uploaded Successfully");
		            } catch (Exception ex) {
		               request.setAttribute("gurumessage", "File Upload Failed due to " + ex);
		            }         		
		        }else{
		
		            request.setAttribute("gurumessage","No File found");
 }
		        request.getRequestDispatcher("/result.jsp").forward(request, response);
		
		    }


}

Explanation of the code:

Code Line 12-14: Here we will have to import org.apache.commons library into the configuration of the code. We will have to import fileupload class from org.apache.commons library.

Code Line 23: Here we have doPost() method, which will be called as we are passing POST method in JSP and it will request and response objects as its parameters

Code Line 26: Here we are creating an object of ServletFileUpload class from fileUpload package from org.apache.commons library which will check whether there are any file objects in JSP. If any found then those file object will be taken from request.

Code Line 27-32: We will iterate the number of files by checking how many file item are present in multiparts object which is a list object (if we upload more than one file) and save it into c:/guru/upload folder with the filename which has been provided. We are writing the file using write method of the fileobject into the folder which has been mentioned.

Code Line 34: If there is no exception then we are setting attribute in request as gurumessage with value "File uploaded successfully".

Code Line 35-36: If exception occurs then setting message that "File upload failed"

Code Line 40: If file not found then setting message as "No file found"

Code Line 42: Forwarding request using requestdispatcher object to result.jsp with request and response objects.

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

Explanation of the code:

Code Line 10: Here we are getting the attribute from the request object with value gurumessage into a string object.

Code Line11: Here we are printing that message.

When we execute the above code we get the following output

Output:

We get a form wherein there is fields to choose a file from directory. Once the file is selected then we have to click on the upload button.

JSP Example

Once the upload button is click we get the message that file is uploaded successfully.

JSP Example

In the below diagram we can see that file had been uploaded in c:/guru/upload folder.

JSP Example

Downloading File:

In this example, we are going to download a file from a directory by clicking on the button.

Downloading_1.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>Downloading Guru Example</title>
</head>
<body>
Guru Downloading File<a href="guru_download">Download here!!!</a>
</body>
</html>

Explanation of the code:

Code Line 10: Here we have given link to download a file from folder c:/guru/upload using servlet guru_download .

Guru_download.java

package demotest;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class guru_download
 */
public class guru_download extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		String gurufile = "test.txt";
		String gurupath = "c:/guru/upload/";
		response.setContentType("APPLICATION/OCTET-STREAM");
		response.setHeader("Content-Disposition", "attachment; filename=\""
				+ gurufile + "\"");
 
		FileInputStream fileInputStream = new FileInputStream(gurupath
				+ gurufile);
 
		int i;
		while ((i = fileInputStream.read()) != -1) {
			out.write(i);
		}
		fileInputStream.close();
		out.close();
	}


	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}

Explanation of the code:

Code Line 3-5: Here we are importing FileInputStream , IO Exception and PrintWriter from the java.io package.

Code Line 15: We are defining guru_download servlet which extends HttpServlet.

Code Line 18: As we have defined a href, which will be enclosed in URL so GET method will get processed (doGet will be called in servlet) which also encloses request and response objects.

Code Line 19-20: We are setting content Type in response object and also get writer object from response.

Code Line 21-22: Defining a variable as gurufile as value test.txt and gurupath as c:/guru/upload/

Code Line 23-25: We are setting the content type using response object and we use setHeader method which sets header into the response object as the filename which has been uploaded.

Code Line 27-28: We are creating FileInputStream in which we will add gurupath+gurufile.

Code Line 31-33: Here we have taken a while loop which will run till the file is read,hence we have given condition as != -1. In this condition we are writing using printwriter object out.

When you execute the above code you will get the following output

Output:

JSP Example

Output:

We have to click on downloading_1.jsp we will get a hyperlink as "Download Here". When you click on this hyperlink file, it will downloaded into the system.

Summary:

  • We have learnt about registration form to register into any application
  • Learnt more about how the login in and logout forms works out.
  • Also learnt about uploading and downloading of a file through JSP.

 

YOU MIGHT LIKE: