FileUploadAction.java
in package net.viralpatel.struts2
. FileUploadAction.java package net.viralpatel.struts2;
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.ActionSupport;
public class FileUploadAction extends ActionSupport implements
ServletRequestAware {
private File userImage;
private String userImageContentType;
private String userImageFileName;
private HttpServletRequest servletRequest;
public String execute() {
try {
String filePath = servletRequest.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;
}
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;
}
@Override
public void setServletRequest(HttpServletRequest servletRequest) {
this.servletRequest = servletRequest;
}
}
Code language: Java (java)
In above class file we have declared few attributes: private File userImage;
-> This will store actual uploaded Fileprivate String userImageContentType;
-> This string will contain the Content Type of uploaded file. private String userImageFileName;
-> This string will contain the file name of uploaded file.private File uploadedFile
, the content type will be uploadedFileContentType and file name uploadedFileFileName. Also note in above action class, we have implemented interface org.apache.struts2.interceptor.ServletRequestAware. This is to get servletRequest object. We are using this path to save the uploaded file in execute()
method. We have used FileUtil.copyFile()
method of commons-io package to copy the uploaded file in root folder. This file will be retrieved in JSP page and displayed to user. <%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Upload User Image</title>
</head>
<body>
<h2>Struts2 File Upload & Save Example</h2>
<s:actionerror />
<s:form action="userImage" method="post" enctype="multipart/form-data">
<s:file name="userImage" label="User Image" />
<s:submit value="Upload" align="center" />
</s:form>
</body>
</html>
Code language: HTML, XML (xml)
SuccessUserImage.jsp <%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Success: Upload User Image</title>
</head>
<body>
<h2>Struts2 File Upload Example</h2>
User Image: <s:property value="userImage"/>
<br/>
Content Type: <s:property value="userImageContentType"/>
<br/>
File Name: <s:property value="userImageFileName"/>
<br/>
Uploaded Image:
<br/>
<img src="<s:property value="userImageFileName"/>"/>
</body>
</html>
Code language: HTML, XML (xml)
<action name="userImage"
class="net.viralpatel.struts2.FileUploadAction">
<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">SuccessUserImage.jsp</result>
<result name="input">UserImage.jsp</result>
</action>
Code language: HTML, XML (xml)
Note that in above entry we have specified two parameter to fileUpload interceptor, maximumSize and allowedTypes. These are optional parameters that we can specify to interceptor. The maximumSize param will set the maximum file size that can be uploaded. By default this is 2MB. And the allowedTypes param specify the allowed content types of file which can be uploaded. Here we have specified it to be an image file (image/png,image/gif,image/jpeg,image/pjpeg). The file upload interceptor also does the validation and adds errors, these error messages are stored in the struts-messsages.properties file. The values of the messages can be overridden by providing the text for the following keys: Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…
Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…
Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…
1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…
GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…
1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…
View Comments
hi viral one help can you autocompleter example in Struts2
hi viral one help can you post autocompleter example in Struts2
I am new to struts 2.This is really a very good example....It helped me a lot....Thanks....
Question : How to store the File in the database(Like Oracle) ??? Can you please provide the code for it???
Thanks in advance....
I am thankful to viral for help me in struts2
Hello! Thanks for this tutorial, it was very helpful. I have one problem. When my form is loaded, it needs some dynamic data to be loaded from my DB(some selects, and labels). It works great if I don't upload wrong file types, but when I try to upload a different kind of file, it doesn't load the dynamic data. If I redirect to the action, it works fine, but then it doesn't show the error message, this is my struts.xml, as you can see, it uses wildcards to handle method invocation:
newTicket.jsp
/WEB-INF/HelpDeskForms/segResponder.jsp
/WEB-INF/HelpDeskForms/segRequester.jsp
/WEB-INF/HelpDeskForms/segAdmSup.jsp
/WEB-INF/HelpDeskForms/newTicket.jsp
/WEB-INF/HelpDeskForms/detRequester.jsp
unassignedByAreaTicket
postCreateTicket
...........
Hi,,, Thanks for the article....
But im not getting output... It says...
userImageFileName is null
and giving NullpointerException
Any extra code to write than you have given above..
I think no but wat is the reason why its giving NullPointerException.......?
Plz... Thanks in advance....
System.out.println("user Image :" + userImage);
System.out.println("user Image Name:" + userImageFileName);
Both are returning null so
File fileToCreate = new File(filePath, getUserImageFileName());
returning NullPointerException
any help plz....
Hi,
The error you have faced - "I have problem with String filePath = servletRequest.getSession().getServletContext().getRealPath(“/”); .It allways return null .And I get a java.lang.NullPointerException
plz I need your help"
can be resolved by adding the following interceptor in your struts.xml since the file upload action you are calling doesnt call the servlet class at that instance.
Interceptor:
example below is the one used in my application
application/vnd.ms-excel
<!-- 10240 10KB -->
2097152
fileUpload.def
Footer.jsp
try to remove the interceptors, this works for me. but its weird... :)
I am really enjoying this tutorial!!! Great job.
Everything is working for me using jboss; however, I noticed that servletRequest.getRealPath...
is coming up with a deprecation message.
What is the replacement for this?
Thanks again!
@swag01: Thanks for pointing out this. ServletRequest.getRealPath() method has been deprecated as the same method is available in
javax.servlet.ServletContext
interface.Thanks Viral;
I made the corrections to the FileUploadAction.java (It didn't like the @override so I commented that out too):
If you want to update your code with the changes, I am fine.
//src
@swag01 - Thanks for the source code. I have updated the above java code and removed call to deprecated method.