Upload a Image Eclipse on Server Directory

This tutorial volition take you on the style to develop a Coffee servlet that handles file upload to server from client, pace past step. A simple Java web application volition be developed to demonstrate upload facility. The awarding consists of:

    • An upload grade that allows user to pick upwards a file to upload.
    • A Coffee servlet that parses the request and saves the uploaded file as a permanent file on the server.
    • A message page that shows successful/mistake messages.

In this tutorial, the application will be developed using Eclipse IDE, and then you are supposed to be familiar with Eclipse.

Table of content:

    1. Setting up environment
    2. Setting upwardly Eclipse project
    3. Coding file upload grade
    4. Creating the servlet
    5. Implementing code to handle file upload
    6. Coding message page
    7. Full code of the servlet class
    8. The generated web.xml file
    9. Testing the application

1. Setting up environment

Before moving on, make sure y'all got the following software installed on your calculator (of course yous can use newer versions):

    • Tomcat vi.0 or newer.
    • JDK/JRE half-dozen.0 or newer.
    • Eclipse IDE for Java EE Developers (Helios 3.six.2) or newer.
    • Apache Common File Upload 1.2.two and Apache Eatables IO 2.3

If yous don't accept ane of the above software installed, download and install them past clicking on an individual link. Afterward downloading the Common File Upload library, extract the zip file to a desired location, and make certain you got a JAR file called eatables-fileupload-1.ii.2.jar under lib directory. Likewise, the Eatables IO library is a dependency for the Common File Upload library, and make sure yous got the JAR file eatables-io-2.3.jar afterward extracting the zip file. These JAR files will be used in the project.

NOTES: In this tutorial, we target the application to Servlet 2.v environment. For Servlet 3.0 or later, nosotros recommend this article: How to write upload file servlet with Servlet 3.0 API.

2. Setting up Eclipse project

2.1. Creating new project

In Eclipse's Coffee EE perspective, select File > New Dynamic Web Project from chief card. In the dialog New Dynamic Spider web Project, blazon UploadServletApp as Project name. Select 2.five from the dropdown list Dynamic web module version:

create project 1

Click Finish. The project is created with some skeleton code.

2.2. Creating Coffee package

Nether src directory, create a new Coffee package chosen net.codejava.upload. The projection's initial structure should look like this:

project structure

2.3. Calculation Tomcat server

Skip this step you take Tomcat already appears in the Servers view.

Switch to Server views (Select Windows >Testify View >Others >Servers from master menu). Right click in the Servers view, select New >Server:

new server

In the dialog New Server, select Tomcat v6.0 Server. Click Next:

select server

In the next screen, click Browse button to select Tomcat'southward installation directory on your reckoner:

select tomcat install dir

NOTES: Yous may not see this screen if you used Tomcat before, as Eclipse remembers Tomcat installation directory so information technology won't inquire you lot.

Click Side by side. In the Add and Remove screen, select UploadServletApp on the left and click Add button to move in to the right:

add app to server

Click Finish, the application UploadServletApp is now configured to run on Tomcat.

ii.4. Making server runtime available to the project

Tomcat provides API to work with Java servlets, so nosotros need to make that API available to the project. Select Project > Properties from chief carte du jour. In the dialog Properties for UploadServletApp, select Targeted Runtimes on the left, and check Apache Tomcat v6.0 on the right:

targeted runtime check

2.5. Calculation required libraries to the project

Re-create two JAR files commons-fileupload-1.ii.2.jar and commons-io-2.3.jar to WebContent\WEB-INF\lib directory under projection directory. The Common File Upload API volition be available to the project and packaged together with the application when creating a State of war file.

2.vi. Testing Tomcat server

In the Servers view, click on the Start push to showtime Tomcat:

start server button

And then switch to Console view, if you come across the final line looks like:

INFO: Server startup in 289 ms

That means the server has started successfully.

And pay attention at the line looks like this:

INFO: Starting Coyote HTTP/one.1 on http-8080

That means the server is listening on the port number 8080.

console view

3. Coding File Upload form

We need to create a JSP page that shows a form which allows user to choice up a file to upload. Right-click on WebContent directory, select New >JSP File from context menu. In the New JSP File dialog, enter name of the JSP folio every bit "upload" under File name field:

new jsp file

Click Stop. The upload.jsp file is created under WebContent directory.

Write code for the upload.jsp file equally follows:

<%@ page language="java" contentType="text/html; charset=UTF-8" 	pageEncoding="UTF-8"%> <!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=UTF-8"> <title>File Upload</title> </caput> <trunk> 	<center> 		<form method="post" action="UploadServlet" enctype="multipart/form-data"> 			Select file to upload: <input type="file" name="uploadFile" /> 			<br/><br/>  			<input blazon="submit" value="Upload" /> 		</grade> 	</center> </trunk> </html>

As you can encounter, the JSP lawmaking is pure HTML. Some noteworthy points are explained as follows:

- The class tag defines the following properties:

    • method="post": when submitting, form's information is sent to server using HTTP POST method. This is required for uploading file because file's content can be sent only via POST method.
    • action="UploadServlet": specifies a relative path on the server that handles file upload. In this case, we utilise the path UploadServlet mapped to a Java servlet that handles file upload.
    • enctype="multipart/form-data": tells the browser that this class may contain upload data so the browser handles accordingly.

- The input tag (type = "file") displays a text field and a Browse push button which allows the user to select a file from his calculator.

- The input tag (type = "submit") displays a submit push labeled as "Upload".

Side by side, we create a servlet to handle file upload from the upload.jsp page.

4. Creating the Servlet

Select File >New > Servlet from chief card. In the Create Servlet dialog:

    • Type or browse the package net.codejava.upload in the field Java packet.
    • Type UploadServlet into the field Class proper noun.

create servlet 1

Click Next. The next screen lets reviewing name and URL mapping of the servlet:

create servlet 2

Note that the URL mapping in this screen must friction match the value of the activeness attribute of the grade defined in the upload.jsp page:

<form method="mail service" action="UploadServlet" enctype="multipart/form-data">

Click Next. The last screen let us determine which methods demand to be generated:

create servlet 3

The merely method nosotros need to implement in the servlet is doPost(), so let check only two check boxes:

    • Inherited abstract methods.
    • doPost.

Click Finish. The servlet UploadServlet course is generated with a skeleton equally follows:

packet com.upload;  import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;  /**  * Servlet implementation class UploadServlet  */ public grade UploadServlet extends HttpServlet { 	private static final long serialVersionUID = 1L;  	/** 	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse 	 *      response) 	 */ 	protected void doPost(HttpServletRequest request, 			HttpServletResponse response) throws ServletException, IOException { 		// TODO Auto-generated method stub 	} }

5. Implementing lawmaking to handle file upload

It's fourth dimension to write actual code for the UploadServlet course to read upload data and relieve information technology every bit a file on disk. Nosotros implement the code in the servlet's doPost() method.

5.1. Defining constants

We define some constants in the servlet as follows:

private static terminal String UPLOAD_DIRECTORY = "upload"; private static concluding int THRESHOLD_SIZE 	= 1024 * 1024 * three; 	// 3MB private static final int MAX_FILE_SIZE 		= 1024 * 1024 * xl; // 40MB individual static final int MAX_REQUEST_SIZE 	= 1024 * 1024 * l; // 50MB

These constants will be used to configure upload settings.

    • UPLOAD_DIRECTORY: proper name of the directory on the server where upload file volition be stored. The directory is chosen to be relative to the web application's directory.
    • THRESHOLD_SIZE: file that has size less than this threshold value will exist saved into retentiveness. If the size is greater than this value, it will exist stored on deejay, temporarily. The value is measured in bytes.
    • MAX_FILE_SIZE: specifies the maximum size of an upload file. We define this constant to concur a file upwardly to 40MB.
    • MAX_REQUEST_SIZE: specifies the maximum size of a HTTP request which contains the upload file and other course's data, and so this constant should be greater than the MAX_FILE_SIZE.

      All sizes are measured in bytes.

5.2. Checking if the request having upload data

Place the post-obit lines of code at the beginning of doPost() method:

// checks if the request actually contains upload file if (!ServletFileUpload.isMultipartContent(asking)) { 	PrintWriter author = response.getWriter(); 	writer.println("Request does non comprise upload data"); 	author.flush(); 	return; }

That checks if the request contains upload information (indicated by the attribute enctype="multipart/form-data" of the upload form). If not, we print a message to the user and leave the method.

5.3. Configuring upload settings

Next, we configure some settings using the constants divers previously:

// configures upload settings DiskFileItemFactory factory = new DiskFileItemFactory(); manufacturing plant.setSizeThreshold(THRESHOLD_SIZE); factory.setRepository(new File(Organization.getProperty("java.io.tmpdir")));  ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(MAX_FILE_SIZE); upload.setSizeMax(MAX_REQUEST_SIZE);

The DiskFileItemFactory class manages file content either in retentivity or on disk. We call setSizeThreshold() method to specify the threshold higher up which files are stored on deejay, under the directory specified by the method setRepository(). In the above code, nosotros specify the temporary directory available for Java programs. Files are stored temporarily in that directory and they will be deleted. So we need to copy the files from the temporary directory to a desired location.

The ServletFileUpload is the main class that handles file upload by parsing the asking and returning a list of file items. It is also used to configure the maximum size of a single file upload and maximum size of the request, by the methods setFileSizeMax()and setSizeMax() respectively.

5.4. Creating directory to store upload file

Because upload files are stored temporarily under a temporary directory, we need to save them under another directory permanently. The following code creates a directory specified by the abiding UPLOAD_DIRECTORY under spider web application's root directory, if it does not exist:

// constructs the directory path to store upload file String uploadPath = getServletContext().getRealPath("") 	+ File.separator + UPLOAD_DIRECTORY; // creates the directory if it does not exist File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { 	uploadDir.mkdir(); }

NOTES: It'due south non recommended to save files under the directory relative to awarding'due south directory, considering when re-deploying/un-deploying the awarding, all files may be lost. Nosotros use this approach for demo purpose only. In practice, you should consider storing files in a location which is independent of the application.

five.v. Reading upload information and save to file

And this is the about of import code: parsing the request to save upload information to a permanent file on disk:

Listing formItems = upload.parseRequest(request); Iterator iter = formItems.iterator();  // iterates over form'due south fields while (iter.hasNext()) { 	FileItem item = (FileItem) iter.adjacent(); 	// processes just fields that are not form fields 	if (!item.isFormField()) { 		String fileName = new File(particular.getName()).getName(); 		Cord filePath = uploadPath + File.separator + fileName; 		File storeFile = new File(filePath);  		// saves the file on disk 		item.write(storeFile); 	} }

The parseRequest() method of ServletFileUpload class returns a list of course items which will be iterated to identify the item (represented past a FileItem   object) which contains file upload data. The method isFormField() of FileItem   class checks if an item is a grade field or not. A non-form field item may contain upload information, thus the check:

if (!item.isFormField()) { }

And to save the file on deejay, we call the write(File) method of FileItem class.

6. Coding bulletin page

Create a new JSP folio called bulletin.jsp under WebContent directory and paste the post-obit code:

<%@ page language="coffee" contentType="text/html; charset=UTF-8" 	pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML iv.01 Transitional//EN"  	"http://world wide web.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Blazon" content="text/html; charset=UTF-viii"> <championship>Upload</championship> </head> <body> 	<middle> 		<h2>${requestScope.message}</h2> 	</center> </body> </html>

The purpose of the message.jsp page is to show value of a property called "message" present in the asking scope, using expression language (EL): ${requestScope.bulletin}

We will laissez passer the actual message from the servlet code.

half dozen.1. Showing letters to the user

It's necessary to show a bulletin to the user to indicate whether the upload is done or there's an error occurred.

In case the upload has been done successfully:

request.setAttribute("bulletin", "Upload has been done successfully!");

And in the other case, there was an mistake occurred:

asking.setAttribute("bulletin", "At that place was an fault: " + ex.getMessage());

Finally, the following code redirects the user to the message.jsp page:

getServletContext().getRequestDispatcher("/message.jsp").forwards(request, response);

7. Total code of the servlet class

The following is complete source lawmaking of the UploadServlet.java class:

package internet.codejava.upload;  import coffee.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Iterator; 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;  /**  * A Java servlet that handles file upload from client.  * @author www.codejava.net  */ public form UploadServlet extends HttpServlet { 	private static final long serialVersionUID = 1L;  	private static final String UPLOAD_DIRECTORY = "upload"; 	individual static concluding int THRESHOLD_SIZE 	= 1024 * 1024 * iii; 	// 3MB 	private static final int MAX_FILE_SIZE 		= 1024 * 1024 * twoscore; // 40MB 	private static final int MAX_REQUEST_SIZE 	= 1024 * 1024 * fifty; // 50MB  	/** 	 * handles file upload via HTTP Postal service method 	 */ 	protected void doPost(HttpServletRequest request, 			HttpServletResponse response) throws ServletException, IOException { 		// checks if the request actually contains upload file 		if (!ServletFileUpload.isMultipartContent(request)) { 			PrintWriter writer = response.getWriter(); 			writer.println("Request does not contain upload data"); 			writer.flush(); 			return; 		} 		 		// configures upload settings 		DiskFileItemFactory manufacturing plant = new DiskFileItemFactory(); 		factory.setSizeThreshold(THRESHOLD_SIZE); 		factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); 		 		ServletFileUpload upload = new ServletFileUpload(factory); 		upload.setFileSizeMax(MAX_FILE_SIZE); 		upload.setSizeMax(MAX_REQUEST_SIZE); 		 		// constructs the directory path to shop upload file 		String uploadPath = getServletContext().getRealPath("") 			+ File.separator + UPLOAD_DIRECTORY; 		// creates the directory if it does non exist 		File uploadDir = new File(uploadPath); 		if (!uploadDir.exists()) { 			uploadDir.mkdir(); 		} 		 		endeavor { 			// parses the request's content to extract file data 			List formItems = upload.parseRequest(request); 			Iterator iter = formItems.iterator(); 			 			// iterates over course'due south fields 			while (iter.hasNext()) { 				FileItem item = (FileItem) iter.next(); 				// processes only fields that are not course fields 				if (!particular.isFormField()) { 					String fileName = new File(item.getName()).getName(); 					String filePath = uploadPath + File.separator + fileName; 					File storeFile = new File(filePath); 					 					// saves the file on disk 					item.write(storeFile); 				} 			} 			request.setAttribute("bulletin", "Upload has been done successfully!"); 		} catch (Exception ex) { 			request.setAttribute("message", "In that location was an error: " + ex.getMessage()); 		} 		getServletContext().getRequestDispatcher("/message.jsp").forward(asking, response); 	} }

As you can encounter, the code that parses the asking and saves upload information is placed within a effort-catch block. In case of exception, we set an error message every bit value for the "message" object. And finally, the servlet forwards user to the message.jsp page.

8. The generated spider web.xml file

Although we don't touch the web.xml file at all, Eclipse generated the lawmaking looks like this:

<?xml version="ane.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-example"  	xmlns="http://coffee.sun.com/xml/ns/javaee"  	xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  		http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  	id="WebApp_ID" version="2.5">   <display-name>UploadServletApp</display-name>    <servlet>     <description></description>     <display-proper noun>UploadServlet</brandish-name>     <servlet-name>UploadServlet</servlet-name>     <servlet-course>cyberspace.codejava.upload.UploadServlet</servlet-form>   </servlet>      <servlet-mapping>     <servlet-name>UploadServlet</servlet-proper noun>     <url-blueprint>/UploadServlet</url-pattern>   </servlet-mapping> </web-app>

nine. Testing the awarding

So far nosotros have washed the coding function. It's fourth dimension to accept a examination to verify the application. Make sure Tomcat is started, open a new browser window and type the following URL into the address bar:

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

The upload course is displayed equally follows:

upload form

Click Browse push and select whatsoever file on your computer, so hitting Upload button. A bulletin page is displayed to betoken the upload has been successful:

upload success message

To bank check if the file is saved successfully to a desired location, verify the file is present inside upload directory which is created nether UploadServletApp directory on the server. In case of this tutorial, since the server is running within Eclipse, the file is saved nether this location:

WORKSPACE\.metadata\.plugins\

org.eclipse.wst.server.cadre\

tmp0\wtpwebapps\UploadServletApp\upload

If y'all deployed the awarding on Tomcat exterior Eclipse, the file would be stored under:

c:\Program Files\Apache Software Foundation\Tomcat vi.0\webapps\UploadServletApp\upload

Related File Upload Tutorials:

  • Coffee File Upload Case with Servlet iii.0 API
  • Jump MVC File Upload Tutorial with Eclipse IDE
  • Upload file with Struts
  • Upload files to database (Servlet + JSP + MySQL)
  • Upload Files to Database with Spring MVC and Hibernate

Other Java Servlet Tutorials:

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

Almost the Writer:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the fourth dimension of Java i.iv and has been falling in love with Java since then. Make friend with him on Facebook and watch his Coffee videos you YouTube.

Add comment

hublerloored.blogspot.com

Source: https://www.codejava.net/java-ee/servlet/eclipse-file-upload-servlet-with-apache-common-file-upload

0 Response to "Upload a Image Eclipse on Server Directory"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel