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 ofAction
interface andvalidate()
method for file processing.interceptor
: ThefileUpload
interceptor is essential for parsing uploaded data.
✅ Implementation Steps
Configure
struts.xml
Add thefileUpload
interceptor to the stack:<interceptors> <interceptor-stack name="fileUploadStack"> <interceptor-ref name="fileUpload"/> <interceptor-ref name="defaultStack"/> </interceptor-stack> </interceptors>
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>
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; } }
Validate File Size/Type
Configure validation instruts.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: