Skip to content Skip to sidebar Skip to footer

Sample .java File to Upload in Servele

Earlier Java EE half-dozen, applications usually have to use an external library like Apache's Common File Upload to handle file upload functionality. Fortunately, developers do no longer take to depend on whatsoever external library, since Coffee EE 6 provides congenital-in file upload API.

Runtime requirement:

    • Java EE 6 with Servlet 3.0.
    • Server: Apache Tomcat 7.0

Of course y'all can use newer versions of Java EE and Tomcat server.

1. File Upload API in Servlet 3.0

The Servlet 3.0 API provides some new APIs for working with upload data:

    • Annotation @MultipartConfig : A servlet can be annotated with this annotation in order to handle multipart/form-data requests which comprise file upload data. The MultipartConfig annotation has the post-obit options:
        • fileSizeThreshold : file's size that is greater than this threshold will exist direct written to deejay, instead of saving in memory.
        • location : directory where file volition be stored via Office.write() method.
        • maxFileSize : maximum size for a single upload file.
        • maxRequestSize :maximum size for a request.

          All sizes are measured in bytes.

    • Interface Part : represents a part in a multipart/form-data request. This interface defines some methods for working with upload information (to proper noun a few):
        • getInputStream(): returns an InputStream object which can be used to read content of the part.
        • getSize(): returns the size of upload information, in bytes.
        • write(String filename): this is the convenience method to save upload information to file on disk. The file is created relative to the location specified in the MultipartConfig annotation.
    • New methods introduced inHttpServletRequest interface:
      • getParts(): returns a drove of Part objects
      • getPart(String proper noun ): retrieves an private Part object with a given name.

These new APIs make our life easier, really! The code to save upload file is very simple, every bit follows:

          for (Role part : request.getParts()) {             String fileName = extractFileName(part);             function.write(fileName);         }

The higher up code just iterates over all parts of the request, and relieve each role to disk using the write() method. The file name is extracted in the following method:

          private Cord extractFileName(Role part) {         String contentDisp = role.getHeader("content-disposition");         String[] items = contentDisp.split(";");         for (String s : items) {             if (s.trim().startsWith("filename")) {                 render s.substring(s.indexOf("=") + 2, s.length()-one);             }         }         render "";     }

Considering file name of the upload file is included in content-disposition header like this:

course-data; name="dataFile"; filename="PHOTO.JPG"

And so the extractFileName() method gets Photograph.JPG out of the string.

Now let'southward apply the new Servlet iii.0's API to build a sample file upload web application.

two. Coding file upload servlet class

Following is source code of the servlet class ( UploadServlet.java):

package net.codejava.servlet; import coffee.io.File; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; @WebServlet("/UploadServlet") @MultipartConfig(fileSizeThreshold=1024*1024*2,	// 2MB  				 maxFileSize=1024*1024*10,		// 10MB 				 maxRequestSize=1024*1024*50)	// 50MB public class UploadServlet extends HttpServlet { 	/** 	 * Proper name of the directory where uploaded files will exist saved, relative to 	 * the spider web application directory. 	 */ 	private static terminal String SAVE_DIR = "uploadFiles"; 	 	/** 	 * handles file upload 	 */ 	protected void doPost(HttpServletRequest request, 			HttpServletResponse response) throws ServletException, IOException { 		// gets absolute path of the web awarding 		String appPath = request.getServletContext().getRealPath(""); 		// constructs path of the directory to salvage uploaded file 		Cord savePath = appPath + File.separator + SAVE_DIR; 		 		// creates the save directory if it does not exists 		File fileSaveDir = new File(savePath); 		if (!fileSaveDir.exists()) { 			fileSaveDir.mkdir(); 		} 		 		for (Part part : request.getParts()) { 			String fileName = extractFileName(role); 			// refines the fileName in case information technology is an absolute path 			fileName = new File(fileName).getName(); 			part.write(savePath + File.separator + fileName); 		} 		asking.setAttribute("bulletin", "Upload has been washed successfully!"); 		getServletContext().getRequestDispatcher("/message.jsp").forward( 				request, response); 	} 	/** 	 * Extracts file name from HTTP header content-disposition 	 */ 	private Cord extractFileName(Part part) { 		String contentDisp = part.getHeader("content-disposition"); 		String[] items = contentDisp.split(";"); 		for (String southward : items) { 			if (s.trim().startsWith("filename")) { 				render s.substring(south.indexOf("=") + 2, southward.length()-one); 			} 		} 		return ""; 	} }

Note that in the servlet's doPost() method, nosotros relieve the uploaded file in a directory named "uploadFiles" which is relative to the spider web application directory. If this directory does non exist, it will be created.

3. Coding JSP upload form

Following is source lawmaking the upload.jsp file:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" 	pageEncoding="ISO-8859-one"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML four.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> <trunk> <center> 	<h1>File Upload</h1> 	<form method="postal service" activeness="UploadServlet" 		enctype="multipart/class-data"> 		Select file to upload: <input type="file" proper name="file" size="sixty" /><br /> 		<br /> <input type="submit" value="Upload" /> 	</form> </centre> </body> </html>

four. Coding JSP upload outcome page

Following is source code the result page (message.jsp):

<%@ page language="coffee" contentType="text/html; charset=ISO-8859-1" 	pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML four.01 Transitional//EN"  	"http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-i"> <title>Upload</championship> </caput> <body> 	<h2>${requestScope.message}</h2> </body> </html>

Notation: In that location is no spider web.xml configuration file because from Servlet 3.0, web.xml becomes optional.

five. Deploying and testing the application

Deploy the UploadServlet30.war file on a Tomcat version that supports Servlet 3.0 API (e.yard. Tomcat 7.0). Type the post-obit URL into browser's address bar:

http://localhost:8080/UploadServlet30/upload.jsp

The upload form appears:

upload form

Click on Cull File button (Chrome) or Browse (FireFox/IE) to pick up a file, and hit Upload. Afterwards the file is uploaded to the server, a successful message appears:

upload success message

The file is stored under:

$TOMCAT_HOME\webapps\UploadServlet30\uploadFiles

Y'all tin can download an Eclipse project or a deployable WAR file in the attachment department.

In addition, you can watch the post-obit video tutorial to see how to use, deploy and examination the project in action:

Related Java File Upload Tutorials:

  • Coffee Multiple Files Upload Example
  • Coffee File Upload Example with Servlet, JSP and Apache Commons FileUpload
  • Jump MVC File Upload Tutorial with Eclipse IDE
  • Upload file with Struts
  • Upload files to database (Servlet + JSP + MySQL)
  • Upload Files to Database with Leap MVC and Hibernate

Other Java Servlet Tutorials:

  • Java Servlet Quick Commencement for beginners (XML)
  • Java Servlet for beginners (annotations)
  • Handling HTML grade data with Java Servlet
  • Coffee File Download Servlet Example

Well-nigh the Writer:

Nam Ha Minh is certified Coffee programmer (SCJP and SCWCD). He started programming with Java in the time of Coffee 1.4 and has been falling in love with Coffee since and then. Make friend with him on Facebook and picket his Coffee videos y'all YouTube.

Add together comment

ricethimpubstur.blogspot.com

Source: https://www.codejava.net/java-ee/servlet/java-file-upload-example-with-servlet-30-api

Post a Comment for "Sample .java File to Upload in Servele"