Struts - SPLessons

Struts 2 File Upload

Home > Lesson > Chapter 14
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Struts 2 File Upload

Struts 2 File Upload

shape Description

File uploading is a challenging task in all the technologies where the developer needs to add more files and has to set the path to store the uploaded files. Struts 2 File Upload automatically work for all the requests and includes files. By using the Struts 2 File Upload Interceptor, which is available in the org.apache.struts2.interceptor.package.FileUploadInterceptor class and included as a part of the defaultStack. Following is an example. 1. Upload the file, take the index file in enctype multipart/form-data and form name is myFile. 2. Forwarded the request to Action class, Action class extends  ActionSuppot class. Then that Action class contains some predefined properties FileContentType, FileName and DestPath. 3. One need to configure the file size and file type in  struts.xml, Then FileAction class gives the response to View pages, like success page or JSP page.

shape Example

Upload a file in the browser page and use the file property File type.

shape Step 1

Create the project directory structure.

shape Step 2

Add the all jar files in lib folder, like struts2 jar files, servlet-api.jar, freemarker-2.3.15.jar.

shape Step 3

Write the View pages, like index.jsp, success.jsp, error.jsp.  index.jsp [java] <%@ 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>File Upload Example using Struts 2</title> </head> <body> <form action="upload" method="post" enctype="multipart/form-data"> <label for="myFile">Upload your file</label> <input type="file" name="myFile" /> <input type="submit" value="Upload"/> </form> </body> </html> [/java] multipart/form-data is significantly more complicated but it allows entire files to be included in the data. success.jsp [java]<%@ page contentType="text/html; charset=UTF-8" %> <%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> <title>File Upload Success</title> </head> <body> <h1>Welcome to SPLessons</h1> You have successfully uploaded <s:property value="myFileFileName"/> User Image: <s:property value="myFile" /> Content Type:<s:property value="myFileContentType" /> File Name: <s:property value="myFileFileName" /> </body> </html>[/java] The property tag is used to get the property value from a class, which will default to the current Action class property if none is specified. error.jsp [java]<%@ page contentType="text/html; charset=UTF-8" %> <%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> <title>File Upload Error</title> </head> <body> Your file is doesn't uploaded, please try again. </body> </html>[/java] If any error occurred while uploading the file then error text will be displayed.

shape Step 4

To Map the URL pattern in web.xml file. web.xml [xml] <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_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>Struts 2</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <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> </web-app> [/xml] The web.xml document is a J2EE file that decides how components of the HTTP solicitation are prepared by the servlet compartment. It is not entirely a Struts2 arrangement document, but rather it is a record that should be designed for Struts2 to work. This file gives a begin point to any web application. The begin purpose of Struts2 application will be a filter characterized in sending descriptor (web.xml). Consequently we will characterize a entry of FilterDispatcher class in web.xml. struts.xml [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.multipart.maxSize" value="1000000" /> <package name="default" extends="struts-default"> <action name="upload" class="com.splessons.UploadFileAction"> <result name="success">/success.jsp</result> <result name="error">/error.jsp</result> </action> </package> </struts> [/xml] UploadFileAction.java [java] package com.splessons; import java.io.File; import org.apache.commons.io.FileUtils; import java.io.IOException; import com.opensymphony.xwork2.ActionSupport; public class UploadFileAction extends ActionSupport { private File myFile; private String myFileContentType; private String myFileFileName; private String destPath; public String getDestPath() { return destPath; } public void setDestPath(String destPath) { this.destPath = destPath; } 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; } public String execute() { /* To specify the destination location */ destPath = "C:/Users/Chinna/Desktop/avi"; try { File destFile = new File(destPath, myFileFileName); FileUtils.copyFile(myFile, destFile); }catch(IOException e) { e.printStackTrace(); return ERROR; } return SUCCESS; } } [/java] Struts 2 comes with an optional action interface (com.opensymphony.xwork2.Action). By implements this interface, it bring some convenient benefits.The java.lang.Throwable.printStackTrace() method prints this throwable and its backtrace to the standard error stream. It prints a stack trace for this Throwable object on the error output stream that is the value of the field System.err.

shape Output

Run the application in server and it display the output in browser. Choose the file and click on browse button.

Summary

shape Key Points

  • File uploading strategy will have separate jar file that needs to be imported.
  • Struts 2 File Upload - Destination path needs to be set in the code to store the uploaded file.
  • Struts 2 File Upload - maximumSize is the parameter will be utilized to specify size of the file.
  • Struts 2 File Upload - allowedTypes is utilized to specify allowed types such as image/png, image/jpg.