Struts 2 provides robust support for handling file uploads in web applications. Below is a concise overview of the key concepts and implementation steps:

🔧 Core Concepts

  • <s:file> Tag: Used to create an HTML file input element in forms.
  • Action Class: Requires implementation of Action interface and validate() method for file processing.
  • interceptor: The fileUpload interceptor is essential for parsing uploaded data.

✅ Implementation Steps

  1. Configure struts.xml
    Add the fileUpload interceptor to the stack:

    <interceptors>
        <interceptor-stack name="fileUploadStack">
            <interceptor-ref name="fileUpload"/>
            <interceptor-ref name="defaultStack"/>
        </interceptor-stack>
    </interceptors>
    
  2. Create Upload Form
    Use <s:file> in JSP:

    <s:form action="upload" method="post" enctype="multipart/form-data">
        <s:file name="myFile" label="Select File"/>
        <s:submit value="Upload"/>
    </s:form>
    
  3. Handle File in Action Class
    Example code snippet:

    public class UploadAction extends ActionSupport {
        private File myFile;
        private String myFileContentType;
        private String myFileFileName;
    
        // Getters and setters for these fields
        public String execute() {
            // File processing logic here
            return SUCCESS;
        }
    }
    
  4. Validate File Size/Type
    Configure validation in struts.xml:

    <action name="upload" class="UploadAction">
        <interceptor-ref name="fileUploadStack"/>
        <param name="maxFileSize">1024000</param> <!-- 1MB -->
        <param name="maxSwallowSize">102400</param>
        <result name="success">uploadSuccess.jsp</result>
    </action>
    

⚠️ Common Issues

  • enctype="multipart/form-data": Must be set in the form tag.
  • File Path: Use <s:property value="myFileFileName"/> to retrieve the uploaded file name.
  • Security: Always sanitize file names to avoid path traversal vulnerabilities.

📚 Related Resources

For deeper exploration:

file_upload
upload_form
file_validation