Struts 2.x : [A Framework from ASF] :: FileUpload Example
Struts 2.x with FileUpload |
FileUpload Example
Example for FileUpload |
Project Structure
MyFileUploadAction.java
package com.javaskool;
import java.io.File;
import org.apache.commons.io.FileUtils;
import com.opensymphony.xwork2.ActionSupport;
public class MyFileUploadAction extends ActionSupport
{
private File fileUpload;
private String fileUploadContentType;
private String fileUploadFileName;
public String destLocation;
public String getFileUploadContentType() {
return fileUploadContentType;
}
public void setFileUploadContentType(String fileUploadContentType) {
this.fileUploadContentType = fileUploadContentType;
}
public String getFileUploadFileName() {
return fileUploadFileName;
}
public void setFileUploadFileName(String fileUploadFileName) {
this.fileUploadFileName = fileUploadFileName;
}
public File getFileUpload() {
return fileUpload;
}
public void setFileUpload(File fileUpload) {
this.fileUpload = fileUpload;
}
public String execute() throws Exception{
String dest="f:\\Anuj\\temp";
try{
System.out.println("Src File name: " + fileUpload);
destLocation="Check your Dst File name: " + dest+"\\"+fileUploadFileName;
System.out.println(destLocation);
File destFile = new File(dest, fileUploadFileName);
FileUtils.copyFile(fileUpload, destFile);
}catch(Exception e){
// e.printStackTrace();
return ERROR;
}
return SUCCESS;
}
public String display() {
return NONE;
}
}
global.properties
#struts.messages.error.uploading - File upload failed
#struts.messages.error.file.too.large - uploaded file is too large
#struts.messages.error.content.type.not.allowed - file content type is not allow
#struts.messages.error.file.extension.not.allowed - file extension is not allow
index.jsp
<a href="fileUploadPage">Click here to attach your file</a>
success.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<body>
<h1>Struts 2 file upload example</h1>
<h2>File Name : <s:property value="fileUploadFileName"/> </h2> <!-- File Name
-->
<h2>Content Type : <s:property value="fileUploadContentType"/></h2> <!-- Type of
File -->
<h2>File : <s:property value="fileUpload"/></h2> <!-- Name of file with
Location-->
<font color=red>File Location : <s:property value="destLocation"/></font> <!--
Name of file with Location-->
</body>
</html>
uploadFile.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri="/struts-tags" prefix="s" %>
<html>
<s:head />
</head>
<body>
<h1>Struts 2 file upload example using <s:file> </h1>
<s:form action="myfileUploadAction" method="POST" enctype="multipart/form-data">
<s:file name="fileUpload" label="Attach Your File" size="40" />
<s:submit value="submit" name="submit" />
</s:form>
</body>
</html>
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.custom.i18n.resources" value="global" />
<package name="p1" extends="struts-default">
<action name="fileUploadPage" class="com.javaskool.MyFileUploadAction"
method="display">
<result name="none">/uploadFile.jsp</result>
</action>
<action name="myfileUploadAction" class="com.javaskool.MyFileUploadAction">
<interceptor-ref name="exception"/> <!-- Maps exceptions to a result. -->
<interceptor-ref name="logger"/><!-- Outputs the name of the Action. This
interceptor logs the start and end of the execution an action (in English-only,
not internationalized). -->
<interceptor-ref name="i18n"/> <!-- Remembers the locale selected for a user's
session. -->
<interceptor-ref name="fileUpload"> <!-- An Interceptor that adds easy access to
file upload support. -->
<param name="allowedTypes">text/plain,,image/png,image/bmp,image/jpeg</param>
<param name="maximumSize">10240</param> <!-- 10KB only -->
</interceptor-ref>
<!-- including interceptor and the defaultStack provided by vendor-->
<!-- Sets the request parameters onto the Action. -->
<!-- dojo..* (anything parameter whose name contains "dojo.") & ^struts..* (any
parameter whose name starts with "struts.")
<param name="excludeParams">dojo..*,^struts..*,^session..*,^request..*,^application..*,^servlet(Request|Response)..*,parameters...*</param>
-->
<interceptor-ref name="params">
<param name="excludeParams">dojo\..*,^struts\..*</param>
</interceptor-ref>
<!-- This interceptor does nothing if the name of the method being invoked is
specified in the excludeMethods parameter. -->
<!-- Performs validation using the validators defined in action-validation.xml
-->
<interceptor-ref name="validation">
<param name="excludeMethods">input,back,cancel,browse</param>
</interceptor-ref>
<!-- In this case input,back,cancel, as well as browse of the action class will
not pass through the workflow process -->
<!-- Calls the validate method in your Action class. If Action errors are
created then it returns the INPUT view. -->
<interceptor-ref name="workflow">
<param name="excludeMethods">input,back,cancel,browse</param>
</interceptor-ref>
<result name="success">/success.jsp</result>
<result name="input">/uploadFile.jsp</result>
</action>
</package>
</struts>
<!--
This interceptor can be forced to ignored parameters, by setting its
excludeParams attribute. This attribute accepts a comma separated list of
regular expressions. When any of these expressions match the name of a
parameter, such parameter will be ignored by the interceptor. Interceptor stacks
defined by Struts already exclude some parameters:
dojo\..* (anything parameter whose name contains "dojo.")
^struts\..* (any parameter whose name starts with "struts.")
This interceptor runs the action through the standard validation framework,
which in turn checks the action against any validation rules (found in files
such as ActionClass-validation.xml) and adds field-level and action-level error
messages (provided that the action implements
com.opensymphony.xwork2.ValidationAware). This interceptor is often one of the
last (or second to last) interceptors applied in a stack, as it assumes that all
values have already been set on the action.
This interceptor does nothing if the name of the method being invoked is
specified in the excludeMethods parameter.
excludeMethods accepts a comma-delimited list of method names. For example,
requests to foo!input.action and foo!back.action will be skipped by this
interceptor if you set the excludeMethods parameter to "input, back".
Note that this has nothing to do with the com.opensymphony.xwork2.Validateable
interface and simply adds error messages to the action. The workflow of the
action request does not change due to this interceptor. Rather, this interceptor
is often used in conjuction with the workflow interceptor.
-->
jar files required in lib folder
Note: List of jar files differ as per project
commons-fileupload-1.2.2
commons-io-2.0.1
commons-lang-2.4
commons-lang3-3.1
commons-logging-1.1.1
commons-logging-api-1.1
freemarker-2.3.19
javassist-3.11.0.GA
ognl-3.0.5
struts2-core-2.3.4
xwork-core-2.3.4
Click Here to download all jar files required for basic Struts 2.x Application
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>04_Struts2WithFileUpload2</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>s2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>s2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
Output
If you enter other contentType, will return below screen.
If you enter file size more than 10KB, will return below screen.
Click here to download complete code with jar files [3.8 MB]
Recent Comments