Struts 2 File Upload & Save Example With Explanation

Struts 2 File Upload & Save Example

Let us see how to work with file uploads in struts 2 frame work, things to remember while working with this type of application

  • See in

    index.jsp

    i have taken <

    s:file  name=”uploadFile”

    i mean my file tag name is uploadFile

  • We used to write

    setters

    ,

    getters

    for this property in

    Action

    class right, but while writing we need to write setters, getters for 2 more properties with names uploadFileFileName  &  uploadFileContentType

  • I mean name format must be

    [

    our file property name

    ]

    ContentType &

    [

    our file property nam

    e

    ]

    FileName

  • Actually at run time struts 2

    container

    will injects the required file details into these properties, and thing is see

    struts.xml

    –  line

    23

    fileUpload

    is the

    predefined

    interceptor class, this will take cares every thing

  • Once file uploaded, struts 2 will stores the file with some temp name, its our responsibility to convert and save that file,  see line numbers 39,40,41,42 in

    Action

    class of LogingEx.java

File Upload E

xample

required files….

  • index.jsp
  • success.jsp
  • web.xml
  • struts.xml
  • LogingEx.java

Directory Structure

index.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<s:head />
</head>

<s:actionerror />

<s:form action="uploadAction" method="POST" enctype="multipart/form-data">
   <s:file name="uploadFile" label="Choose File" size="40" />
   <s:submit value="Upload" name="submit" />
</s:form>

success.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>

   File uploaded successfully...!!!

   File Name : <s:property value="uploadFileFileName"/> <br>
   Content Type : <s:property value="uploadFileContentType"/> <br>
   Temp File Name : <s:property value="uploadFile"/>

LogingEx.java

package java4s;
import java.io.File;

import org.apache.commons.io.FileUtils;

import com.opensymphony.xwork2.ActionSupport;

public class LogingEx extends ActionSupport{
	private static final long serialVersionUID = 1L;

	private File uploadFile;
	private String uploadFileContentType;
	private String uploadFileFileName;	

	public File getUploadFile() {
		return uploadFile;
	}
	public void setUploadFile(File uploadFile) {
		this.uploadFile = uploadFile;
	}

	public String getUploadFileContentType() {
		return uploadFileContentType;
	}
	public void setUploadFileContentType(String uploadFileContentType) {
		this.uploadFileContentType = uploadFileContentType;
	}

	public String getUploadFileFileName() {
		return uploadFileFileName;
	}
	public void setUploadFileFileName(String uploadFileFileName) {
		this.uploadFileFileName = uploadFileFileName;
	}

	public String execute()
	{
		try{
		String filePath = "c:/Myuploads";  // Path where uploaded file will be stored
        System.out.println("Server path:" + filePath); // check your path in console
        File fileToCreate = new File(filePath, uploadFileFileName);// Create file name  same as original
        FileUtils.copyFile(uploadFile, fileToCreate); // Just copy temp file content tos this file		

		}catch(Exception e)
		{
			e.printStackTrace();
            addActionError(e.getMessage());
            return INPUT;

		}
		return SUCCESS;
	}

}
// Context pirnt.....

//private HttpServletRequest servletRequest;
//String filePath = servletRequest.getSession().getServletContext().getRealPath("/");
//System.out.println("Server path:" + filePath);
//File fileN = new File(filePath, this.uploadFileFileName);
//FileUtils.copyFile(this.userImage, fileToCreate);

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>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

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>
    <include file="struts-default.xml"/>
    <package name="a" extends="struts-default">

        <action name="uploadAction" class="java4s.LogingEx"> 

            <interceptor-ref name="exception" />
			<interceptor-ref name="alias" />
			<interceptor-ref name="servletConfig" />
			<interceptor-ref name="prepare" />
			<interceptor-ref name="i18n" />
			<interceptor-ref name="chain" />
			<interceptor-ref name="debugging" />
			<interceptor-ref name="profiling" />
			<interceptor-ref name="scopedModelDriven" />
			<interceptor-ref name="modelDriven" />
			<interceptor-ref name="fileUpload">
			<param name="maximumSize">10240</param>
			<param name="allowedTypes">text/plain</param>
			</interceptor-ref>
			<interceptor-ref name="checkbox" />
			<interceptor-ref name="staticParams" />
			<interceptor-ref name="actionMappingParams" />
			<interceptor-ref name="params">
			<param name="excludeParams"> dojo\..*,^struts\..*</param>
			</interceptor-ref>
			<interceptor-ref name="conversionError" />
			<interceptor-ref name="validation">
			<param name="excludeMethods"> input,back,cancel,browse</param>
			</interceptor-ref>
			<interceptor-ref name="workflow">
			<param name="excludeMethods"> input,back,cancel,browse</param>
			</interceptor-ref>

            <result name="success">/success.jsp</result>
            <result name="input">/index.jsp</result>
        </action>
    </package>
</struts>

Output

Output If if we take wrong file

Output If file accepted

 

​ ​​

You Might Also Like

  ::. About the Author .::

Java4s_Author Sivateja Kandula – Java/J2EE Full Stack Developer

Founder of Java4s – Get It Yourself, A popular Java/J2EE Programming Blog, Love Java and UI frameworks.
You can sign-up for the Email Newsletter for your daily dose of Java tutorials.

Founder of Java4s – Get It Yourself, A popular Java/J2EE Programming Blog, Love Java and UI frameworks.You can sign-up for thefor your daily dose of Java tutorials.