Jow to Upload a File Using Jsp

In this instance, 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 tin upload any files using JSP.
  • It can be a text file, binary file, epitome file or any other certificate.
  • Here in instance of file uploading, only Mail service method volition be used and non the GET method.
  • Enctype attribute should exist fix to multipart/class-data.

Example: Using Activeness

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

Action_file.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"     pageEncoding="ISO-8859-one"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML iv.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-one"> <championship>Guru File</championship> </caput> <trunk> <a>Guru File Upload:</a> Select file: <br /> <form activeness="action_file_upload.jsp" method="mail service"                         enctype="multipart/course-data"> <input type="file" proper name="file" size="50" /> <br /> <input blazon="submit" value="Upload File" /> </form> </torso> </html>          

Action_file_upload.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-i"     pageEncoding="ISO-8859-one"%>     <%@ page import="java.io.*,java.util.*, javax.servlet.*" %> <%@ page import="javax.servlet.http.*" %> <%@ page import="org.apache.commons.fileupload.*" %> <%@ page import="org.apache.eatables.fileupload.disk.*" %> <%@ page import="org.apache.eatables.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-Blazon" content="text/html; charset=ISO-8859-1"> <title>Guru File Upload</title> </caput> <torso> <%    File file ;    int maxFileSize = 5000 * 1024;    int maxMemSize = 5000 * 1024;    String filePath = "Due east:/guru99/data";     Cord contentType = request.getContentType();    if ((contentType.indexOf("multipart/form-data") >= 0)) {        DiskFileItemFactory factory = new DiskFileItemFactory();       factory.setSizeThreshold(maxMemSize);       manufacturing plant.setRepository(new File("c:\\temp"));       ServletFileUpload upload = new ServletFileUpload(factory);       upload.setSizeMax( maxFileSize );       try{           Listing 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 () )  {                 Cord 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("</torso>");          out.println("</html>");       }grab(Exception ex) {          System.out.println(ex);       }    }else{       out.println("<html>");       out.println("<trunk>");       out.println("<p>No file uploaded</p>");        out.println("</body>");       out.println("</html>");    } %> </body> </html>          

Explanation of the lawmaking:

Action_file.jsp

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

Action_file_upload.jsp

Lawmaking Line 20: Hither we are giving the file path to a particular path

Code Line 23-38: Here we check whether the content blazon is multipart/form-information. If that is the instance, then the content is of file type, and information technology is read. After file being read, it is written into the temporary file and so the temporary file gets converted to the primary file.

When you execute the to a higher place code, y'all 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 case, we are going to upload a file using JSP operations.

We volition take a form which will take "upload" push and when yous click on upload push button and then the file will be uploaded.

Uploading_1.jsp

<%@ page linguistic communication="java" contentType="text/html; charset=ISO-8859-i"     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-ane"> <title>Guru Uploading File</title> </head> <trunk> File: <br /> <form activity="guru_upload" method="post"                         enctype="multipart/grade-data"> <input type="file" name="guru_file" size="l" /> <br /> <input type="submit" value="Upload" /> </class> </torso> </html>          

Explanation of the code:

Code Line 11-12: Here nosotros are taking a form which has action on servlet guru_upload which will laissez passer through a method Mail service. Also, hither we enctype i.east. attribute which specifies how form information should be encoded and sent to server and it is only used with Postal service method. Hither nosotros are setting as multipart/form-information which is for the file(as data will exist big).

Lawmaking Line 13: Here nosotros are specifying guru_file element with type file and giving size as fifty.

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

Guru_upload.java

parcel 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.eatables.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 detail : multiparts){ 		                    if(!item.isFormField()){ 		                        Cord name = new File(item.getName()).getName(); 		                        item.write( new File("c:/guru/upload" + File.separator + proper noun)); 		                    } 		                } 		               //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 constitute");  } 		        asking.getRequestDispatcher("/consequence.jsp").forward(request, response); 		 		    }   }          

Caption of the code:

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

Lawmaking Line 23: Hither we have doPost() method, which will be called every bit 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 volition cheque whether there are any file objects in JSP. If any found then those file object will exist taken from asking.

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 than i file) and save it into c:/guru/upload folder with the filename which has been provided. Nosotros are writing the file using write method of the fileobject into the binder which has been mentioned.

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

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

Lawmaking Line 40: If file not found then setting bulletin as "No file constitute"

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

Event.jsp

<%@ folio language="java" contentType="text/html; charset=ISO-8859-1"     pageEncoding="ISO-8859-i"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML four.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Blazon" content="text/html; charset=ISO-8859-1"> <championship>Guru Outcome</title> </caput> <body> <% Cord msg = (String)request.getAttribute("bulletin");    out.println(msg); %> </body> </html>          

Caption 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: Hither we are printing that message.

When we execute the above code we get the post-obit output

Output:

We get a class wherein there is fields to choose a file from directory. Once the file is selected and so we have to click on the upload push.

JSP Example

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

JSP Example

In the below diagram we tin can encounter 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-ane"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML four.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Blazon" content="text/html; charset=ISO-8859-1"> <title>Downloading Guru Example</championship> </head> <body> Guru Downloading File<a href="guru_download">Download here!!!</a> </body> </html>          

Explanation of the code:

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

Guru_download.coffee

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 form guru_download  */ public class guru_download extends HttpServlet { 	individual 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 lawmaking:

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

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

Code Line 18: Every bit we accept defined a href, which will be enclosed in URL and then GET method will get processed (doGet volition be called in servlet) which also encloses asking and response objects.

Lawmaking Line xix-twenty: Nosotros are setting content Type in response object and also get writer object from response.

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

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

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

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

When you execute the above code y'all will go the following output

Output:

JSP Example

Output:

We accept to click on downloading_1.jsp we will go a hyperlink every bit "Download Here". When y'all click on this hyperlink file, it will downloaded into the system.

Summary:

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

ruizafrown1953.blogspot.com

Source: https://www.guru99.com/jsp-file-upload-download.html

0 Response to "Jow to Upload a File Using Jsp"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel