File upload using struts 2.x

Leave a Comment

This tutorial demonstrates file upload in struts 2.x.


 I am using eclipse IDE for this example.
1. copy following jar files to web contents/WEB-INF/lib 
2. Create jsp file index.jsp in web contents and copy following code:
 <%@ 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 User Image</title>
    </head>

    <body>
        <h2>Struts2 File Upload & Save Example</h2>
        <s:actionerror />
        <s:form action="upload" method="post" enctype="multipart/form-data">
            <s:file name="userImage" label="User Image" />
            <s:submit value="Upload" align="center" />
        </s:form>
    </body>
</html>
 3. create jsp page success.jsp and copy following code:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Success Page For File Upload</title>
    </head>
    <body>
        <h1>Success Page!</h1>
        User Image:<s:property value="userImage"/>
        <br/>
        Content Type:<s:property value="userImageContentType"/>
        <br/>
        File Name: <s:property value="userImageFileName"/>
        <br/>
        Uploaded Image:
        <img src="<s:property value="userImageFileName"/>"/>
    </body>
</html> 
4. Now create configuration file struts.xml and copy following code:
<?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="strutst.devMode" value="true" />
    <package name="default" extends="struts-default">
        <action name="upload" class="com.action.FileUploadAction"
            method="upload">
            <interceptor-ref name="fileUpload">
                <param name="maximumSize">2097152</param>
                <param name="allowedTypes">image/png,image/gif,image/jpeg,image/pjpeg</param>
            </interceptor-ref>
            <interceptor-ref name="defaultStack"></interceptor-ref>
            <result name="success">success.jsp</result>
            <result name="input">index.jsp</result>
            <result name="error">error.jsp</result>
        </action>
    </package>
</struts>
5. Make changes to web.xml as follow:
<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <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>
 6. Create action class FileUploadAction.java and copy following code:
package com.action;
import java.io.File;

import javax.servlet.http.HttpServletRequest;

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

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;

public class FileUploadAction extends ActionSupport implements ServletRequestAware {

    private File userImage;
    private String userImageContentType;
    private String userImageFileName;

    public File getUserImage() {
        return userImage;
    }

    public void setUserImage(File userImage) {
        this.userImage = userImage;
    }

    public String getUserImageContentType() {
        return userImageContentType;
    }

    public void setUserImageContentType(String userImageContentType) {
        this.userImageContentType = userImageContentType;
    }

    public String getUserImageFileName() {
        return userImageFileName;
    }

    public void setUserImageFileName(String userImageFileName) {
        this.userImageFileName = userImageFileName;
    }
   
    private HttpServletRequest request;
   
    public String upload(){
        try {
            String filePath = request.getSession().getServletContext().getRealPath("/");
            System.out.println("Server Path:"+filePath);
            File fileToCreate = new File(filePath, this.userImageFileName);
           
            FileUtils.copyFile(this.userImage, fileToCreate);
           
        } catch(Exception e){
            e.printStackTrace();
            addActionError(e.getMessage());
            return INPUT;
        }
        return SUCCESS;
    }
   
    @Override
    public void setServletRequest(HttpServletRequest request) {
        this.request=request;
    }

}

0 comments:

Post a Comment