Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to upload a file to web server using struts framework

In this article, we will learn how to upload a file using html form and the process to manipulate the uploaded file using struts 2 framework.

When a file is being uploaded using a html form. It is required to have a script that can handle the uploaded file so that the uploaded file could be manipulated for an action or saved as a permanent storage. Struts 2 framework provides a built-in support for file upload using Struts 2 Interceptor mechanism.

File Upload using Struts 2 Framework in detail:

Struts 2 framework provides support for file upload operation using FileUploadInterceptor class defined in org.apache.struts2.interceptor package. The FileUploadInterceptor class provides an interceptor called FileUpload. This interceptor is included as a part of the defaultstack. We create an application interface that will upload a file using a html form and will process this file to “upload” action that will manipulate uploaded file using FileUpload interceptor and will response to user with message, if the file has been uploaded into the specific directory or not.

First of all, create an html form that uploads a file on the server as follows:

Listing 1: index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Upload Image File</title>
</head>
<body>
   <form action="upload" method="post" enctype="multipart/form-data">
      <label for="myFile">Upload an Image file</label>
      <input type="file" name="myFile" />
      <input type="submit" value="Upload"/>
   </form>
</body>
</html>

The above code creates an html interface to the user to upload a file on the server. This code creates an html form that hits on “uploadfile” action with method type “post” and the attribute “enctype” inform the server that a file is being sent to be uploaded on the server. It contains an attribute of file type that can be accessed by “myFile” name. A submit button is created with the value “Upload File” that will process the html form.

Listing 2: success.jsp

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>File Upload Successful</title>
</head>
<body>
Your file <s:property value="myFileFileName"/> has been uploaded successfully.
</body>
</html>

Once the control has been transferred to uploadfile action and a file has been uploaded successfully on the server, a user should be notified by a successful message as a file has been uploaded successfully on the server.

Listing 3: error.jsp

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>File Upload Error</title>
</head>
<body>
Unable to upload a file, something went wrong.
</body>
</html>

If there goes something wrong, while uploading a file on the server, user should be notified by a message. This is done using error.jsp file. When an error occurred, the control is transferred to error.jsp page to be displayed to the user.

Listing 4: UploadFile.java Action Class

package com.upload.file;

import java.io.File;
import org.apache.commons.io.FileUtils;
import java.io.IOException;
import com.opensymphony.xwork2.ActionSupport;

public class UploadFile extends ActionSupport{
   private File myFile;
   private String myFileContentType;
   private String myFileFileName;
   private String destPath;

   public String execute()
   {
      /* Copy file to a safe location */
      destPath = "C:/apache-tomcat-6.0.33/work/";

      try{
     	 System.out.println("Src File name: " + myFile);
     	 System.out.println("Dst File name: " + myFileFileName);
     	    	 
     	 File destFile  = new File(destPath, myFileFileName);
    	 FileUtils.copyFile(myFile, destFile);
  
      }catch(IOException e){
         e.printStackTrace();
         return ERROR;
      }

      return SUCCESS;
   }
   public File getMyFile() {
      return myFile;
   }
   public void setMyFile(File myFile) {
      this.myFile = myFile;
   }
   public String getMyFileContentType() {
      return myFileContentType;
   }
   public void setMyFileContentType(String myFileContentType) {
      this.myFileContentType = myFileContentType;
   }
   public String getMyFileFileName() {
      return myFileFileName;
   }
   public void setMyFileFileName(String myFileFileName) {
      this.myFileFileName = myFileFileName;
   }
}

The above code defines an action class named UploadFile that extends ActionSupport class defined in com.opensymphony.xwork2 package. I also define one File type and three String type variables and create their getter() and setter() mthods. This class also define a execute() method that moves the uploaded file to the destination driver (c: drive) using copyFile() method and File() constructor that accepts two parameters as “destination-string” and “uploaded-file-name”. The copyFile() method accepts two parameters as “uploaded-file-ref” and “destination-information-by-file-object” and return “SUCCESS”.

When a file has been uploaded by an html form it hits deployment descriptor file web.xml on the web server.

Listing 5: web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.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">
  <filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <welcome-file-list>
    <welcome-file>error.jsp</welcome-file>
  </welcome-file-list>
</web-app>

The above code defines that the index.jsp file will loaded to be deployed by default at the time of application deployment. All request are hitting to web server will be transferred to struts.xml file using FilterDispatcher class defined in org.apache.struts2.dispatcher package. A and its sub-tag is used to define a list of file or file to be loaded on an application deployment. A <filter> and <filter-mapping> tags are used to defining the mapping between FilterDispatcher class and all the hitting url by client application which are to be transferred to the struts.xml file.

Listing 6: struts.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
	<constant name="struts.devMode" value="true" />
	<constant name="struts.multipart.maxSize" value="1000000" />
	<package name = "default" extends = "struts-default"> 
			<default-action-ref name="index" />
			<action name="index">
	            <result>/index.jsp</result>
	        </action>
	</package>
	<package name="upload" extends = "struts-default">
		<action name="upload" class = "com.upload.file.UploadFile">
			<interceptor-ref name="basicStack"/>
		       <interceptor-ref name="fileUpload">
		           <param name="allowedTypes">image/jpeg,image/gif</param>
		       </interceptor-ref>
            <result name="success">/success.jsp</result>
            <result name="error">/error.jsp</result>
        </action>
	</package>
</struts>

The above code defines the struts.xml configuration file that manages the request coming to upload and move a file to permanent directory. There are two constant variable provided by FileUpload interceptor:

Struts.devMode and struts.multipart.maxSize, their value should be “true” and “max-file-size” as integer for the uploaded file. tag defines an action using sub-tag <action> that hits to class UploadFile inside package com.upload.file package. Two interceptor refrence is defined with the name “basicStatck” and “fileUpload” to limit uploading file type.

index.jsp file to upload a file on the server.

Figure 1: index.jsp file to upload a file on the server.

This figure shows how to upload a file on the server.

File uploaded successfully

Figure 2: File uploaded successfully

The above figure shows success.jsp file, while a file has been uploaded successfully on the server.

File upload error

Figure 3: File upload error

The figure shows the error.jsp file, while there is something wrong or wrong file type was tried to upload on the server.

Directory Structure

Figure 4: Directory Structure

The above file shows the directory structure in Eclipse IDE.

Required Jar Files List

Figure 5: Required Jar Files List

The above figure shows a list of required jar files.

Required Tool & Applications:

To create this application, we are required to have an Eclipse IDE, a web application server like Tomcat Apache, JDK Run time environment like JDK5 and a bundle of Struts 2.0 Jar files.

Conclusion:

In this article, we learn:

  • How do we upload a file using html form?
  • How do we manipulate the uploaded file using struts 2 framework?


Have good knowledge on Java, HTML, CSS and Android platform and is pursuing Masters in Computer Applications.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login