File Upload in struts 2

This is 6 of 8 part of struts 2 tutorial.In this tutorial we will learn how to upload file to server in struts 2 and also how save uploaded file on directory of server machine.

Tutorial Content:

Part-1:Introduction to struts 2
Part-2:configuring struts 2 in eclipse
Part-3:Struts 2 hello world example
Part-4:Login page with validation in struts 2
Part-5:Struts 2 interceptors with example
Part-6:File upload in struts 2
Part-7:Struts 2 ajax example
Part-8:Struts 2 spring 3 integration example 


Struts 2 file upload component can be used to upload mulitpart file in struts 2 application.Struts 2 utilizes in built File upload interceptor for uploading files in struts 2 application.The Struts 2 File Upload Interceptor is based on MultiPartRequestWrapper, which is automatically applied to the request if it contains the file element.

Required jar :
We need to have 1 jar common-io.jar in your classPath.In configuring struts 2 in eclipse post,we have already added jar in classPath.
Create project named "fileUploadInStruts2".For configuring struts 2 in your eclipse ide please refer configuring struts 2 link.

Project stucture:

Action class: 

For adding file uploading functionality in struts 2,We will create action class named FileUploadAction.java.
Create FileUploadAction.java file under src folder in package org.arpit.javaPostsForLearning.

copy following content in FileUploadAction.java

package org.arpit.javaPostsForLearning;
import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.interceptor.ServletRequestAware;

import com.opensymphony.xwork2.ActionSupport;


public class FileUploadAction extends ActionSupport implements ServletRequestAware {

    private File toBeUploaded;
    private String toBeUploadedFileName;
    private String toBeUploadedContentType;
    private HttpServletRequest servletRequest;
    public String execute()
    {
         String filePath = servletRequest.getSession().getServletContext().getRealPath("/");
         File fileToCreate = new File(filePath, this.toBeUploadedFileName);

         try {
            FileUtils.copyFile(this.toBeUploaded, fileToCreate);
        } catch (IOException e) {
            addActionError(e.getMessage());
        }
        return SUCCESS;
    }
    public File getToBeUploaded() {
        return toBeUploaded;
    }
    public void setToBeUploaded(File toBeUploaded) {
        this.toBeUploaded = toBeUploaded;
    }
    public String getToBeUploadedFileName() {
        return toBeUploadedFileName;
    }
    public void setToBeUploadedFileName(String toBeUploadedFileName) {
        this.toBeUploadedFileName = toBeUploadedFileName;
    }
    public String getToBeUploadedContentType() {
        return toBeUploadedContentType;
    }
    public void setToBeUploadedContentType(
            String toBeUploadedFileNameContentType) {
        this.toBeUploadedContentType = toBeUploadedFileNameContentType;
    }
    @Override
    public void setServletRequest(HttpServletRequest servletRequest) {
        this.servletRequest=servletRequest;
        
    }
    
}
Now we have declared three attributes here

 private File toBeUploaded  //Actual file to be uploaded
 private String toBeUploadedFileName // file name of actual file to be uploaded
 private String toVeUploadedContentType  // content type of actual file to be uploaded

We have provided getters and setters for above attributes.So struts 2 automatically set these value according to file being uploaded.
For example if your file name is "sampleFile" then struts 2 interceptor add three parameters to request.
Three parameters are:
[sampleFile]:file
[sampleFile]FileName:String
[sampleFile]ContentType:String

you can notice here that we have given our action class attributes in same format so it will automatically set these attributes according to file being uploaded.

One more thing is that we have implemented "ServletRequestAware" interface in our action class
This is to get ServletRequest object.This request object is required to get path of server machine where file is to be uploaded.

JSPs:

We will create two jsp files here.fileUpload.jsp will display form for uploading file.On clicking on upload button,File will be saved on server machine and request will be forwarded to uploadSucceed.jsp which will render fileName,content type and uploaded image.

fileUpload.jsp:

Create fileUpload.jsp under WebContent folder.
Copy following content to fileUpload.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>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>file upload page</title>
</head>
<body bgColor="lightblue">
<s:form action="fileUpload" method="post" enctype="multipart/form-data">
    <s:file name="toBeUploaded" label="Choose file to upload" />
    <s:submit value="Upload" align="center"/>
</s:form>
</body>
</html>

We have used <s:file> tag for file upload interface.

uploadSucceed.jsp:
Create jsp named "uploadSucceed.jsp" under WebContent folder.
Copy following content into uploadSucceed.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>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Upload Successful</title>
<s:head />
</head>
<body>
File Name :
<s:property value="toBeUploadedFileName"></s:property>
Content type:
<s:property value="toBeUploadedContentType"></s:property>
User file :
<s:property value="toBeUploaded"></s:property>
Uploaded file:
<img src="<s:property value="toBeUploadedFileName"/>"></img>
</body>
</html>

Struts.xml:

Create struts.xml under src folder.
Copy following content to 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>
    <package name="default" extends="struts-default" namespace="/">
        <action name="fileUpload" class="org.arpit.javaPostsForLearning.FileUploadAction">
            <interceptor-ref name="fileUpload">
                <param name="maximumSize">1048576</param>
                <param name="allowedTypes">
                    image/png,image/gif,image/jpeg,image/pjpeg
        </param>
            </interceptor-ref>
            <interceptor-ref name="defaultStack"></interceptor-ref>
            <result name="success">uploadSucceed.jsp</result>
            <result name="input">fileUpload.jsp</result>
        </action>
    </package>
</struts> 

Web.xml:

It is same as in previous posts except that we have changed welcome file to "fileUpload.jsp"
Copy following content into web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" 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_5.xsd">

 <display-name>fileUploadInStruts2</display-name>
 <filter> 
    <filter-name>
      struts2
    </filter-name>
    <filter-class>
      org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
    </filter-class> 
 </filter>

 <filter-mapping>
 <filter-name>struts2</filter-name>
 <url-pattern>/*</url-pattern>    </filter-mapping>

 <welcome-file-list>
 <welcome-file>fileUpload.jsp</welcome-file>
 </welcome-file-list>

</web-app>

Run project:

Right click on project ->run as->run on server
copy resultant url(http://localhost:8080/fileUploadInStruts2/) to your browser.


Now we will browse here text file and click upload.Following screen will appear





















Now again copy http://localhost:8080/fileUploadInStruts2/ url to your browser and press enter
you will get first screen again.We will browse image file named "nature.jpeg" and click on upload.
you will get following screen


















Source code:

Source:Download without jars files 
Source + lib: Download with jars files

Now in next post,we will write struts 2 ajax example.

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012