Struts 2 File Upload and Save Tutorial with Example

Struts 2 Tutorial: Struts 2 File Upload and Save Tutorial with Example

01.19.2010
Email Views: 51070

Welcome to Part-6 of 7-part series of Struts2 Framework. In previous part we went through basics of Struts2 Interceptors. Also we created a custom interceptor and integrated it through Struts2 application.

It is strongly recommended to go through previous articles in case you new to Struts2 Framework.

Struts 2 Tutorial List

Today we will see how to do File Upload in Struts2. We will use Struts2 built-in FileUploadInterceptor in our example to upload the file. 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 file

Before we start, we need to make sure commons-io.jar file is present in the classpath. Following are the list of required Jar files.
struts2-file-upload-jar-files

Getting Started

In order to add file upload functionality we will add an action class FileUploadAction to our project. Create file FileUploadAction.java in package net.viralpatel.struts2.
FileUploadAction.java

01. package net.viralpatel.struts2;
02.  
03. import java.io.File;
04. import javax.servlet.http.HttpServletRequest;
05. import org.apache.commons.io.FileUtils;
06. import org.apache.struts2.interceptor.ServletRequestAware;
07. import com.opensymphony.xwork2.ActionSupport;
08.  
09. public class FileUploadAction extends ActionSupport implements
10. ServletRequestAware {
11. private File userImage;
12. private String userImageContentType;
13. private String userImageFileName;
14.  
15. private HttpServletRequest servletRequest;
16.  
17. public String execute() {
18. try {
19.  
20. String filePath = servletRequest.getRealPath("/");
21. System.out.println("Server path:" + filePath);
22. File fileToCreate = new File(filePath, this.userImageFileName);
23.  
24. FileUtils.copyFile(this.userImage, fileToCreate);
25. } catch (Exception e) {
26. e.printStackTrace();
27. addActionError(e.getMessage());
28.  
29. return INPUT;
30. }
31. return SUCCESS;
32. }
33.  
34. public File getUserImage() {
35. return userImage;
36. }
37.  
38. public void setUserImage(File userImage) {
39. this.userImage = userImage;
40. }
41.  
42. public String getUserImageContentType() {
43. return userImageContentType;
44. }
45.  
46. public void setUserImageContentType(String userImageContentType) {
47. this.userImageContentType = userImageContentType;
48. }
49.  
50. public String getUserImageFileName() {
51. return userImageFileName;
52. }
53.  
54. public void setUserImageFileName(String userImageFileName) {
55. this.userImageFileName = userImageFileName;
56. }
57.  
58. @Override
59. public void setServletRequest(HttpServletRequest servletRequest) {
60. this.servletRequest = servletRequest;
61.  
62. }
63. }

In above class file we have declared few attributes:

  • private File userImage; -> This will store actual uploaded File
  • private 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.

The fields userImageContentType and userImageFileName are optional. If setter method of these fields are provided, struts2 will set the data. This is just to get some extra information of uploaded file. Also follow the naming standard if you providing the content type and file name string. The name should be ContentType and FileName. For example if the file attribute in action file is 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.

The JSPs

Create two JSP file in WebContent folder. UserImage.jsp will display a form to user to upload image. On submit, the file will be uploaded and saved on server. User will be sent to SuccessUserImage.jsp file where File details will be displayed. Copy following code into it.
UserImage.jsp

01. <%@ page contentType="text/html; charset=UTF-8"%>
02. <%@ taglib prefix="s" uri="/struts-tags"%>
03.  
04. <html>
05. <head>
06. <title>Upload User Image</title>
07. </head>
08.  
09. <body>
10. <h2>Struts2 File Upload & Save Example</h2>
11.  
12. <s:actionerror />
13. <s:form action="userImage" method="post" enctype="multipart/form-data">
14. <s:file name="userImage" label="User Image" />
15.  
16. <s:submit value="Upload" align="center" />
17. </s:form>
18. </body>
19. </html>

SuccessUserImage.jsp

01. <%@ page contentType="text/html; charset=UTF-8"%>
02. <%@ taglib prefix="s" uri="/struts-tags"%>
03. <html>
04. <head>
05. <title>Success: Upload User Image</title>
06.  
07. </head>
08. <body>
09. <h2>Struts2 File Upload Example</h2>
10. User Image: <s:property value="userImage"/>
11.  
12.  
13.  
14. Content Type: <s:property value="userImageContentType"/>
15.  
16.  
17. File Name: <s:property value="userImageFileName"/>
18.  
19.  
20.  
21. Uploaded Image:
22.  
23.  
24. <img src="<s:property value="userImageFileName"/>"/>
25. </body>
26. </html>

Struts.xml entry

Add following entry for FileUploadAction class to struts.xml file.

01. <action name="userImage"
02. class="net.viralpatel.struts2.FileUploadAction">
03. <interceptor-ref name="fileUpload">
04. <param name="maximumSize">2097152</param>
05.  
06. <param name="allowedTypes">
07. image/png,image/gif,image/jpeg,image/pjpeg
08. </param>
09. </interceptor-ref>
10. <interceptor-ref name="defaultStack"></interceptor-ref>
11. <result name="success">SuccessUserImage.jsp</result>
12.  
13. <result name="input">UserImage.jsp</result>
14. </action>

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:

  • struts.messages.error.uploading – error when uploading of file fails
  • struts.messages.error.file.too.large – error occurs when file size is large
  • struts.messages.error.content.type.not.allowed – when the content type is not allowed

That’s All Folks

Compile and Execute the project in eclipse and goto link http://localhost:8080/StrutsHelloWorld/UserImage.jsp
Image Upload Screen
struts2-file-upload-example

Image Upload Screen in case of error
struts2-file-upload-error
Image Upload Screen on success
struts2-file-upload-success

Download Source Code

Click here to download Source Code without JAR files (20KB)

Moving On

Struts2 makes life very easy. It was like a piece of cake to implement File Upload with Struts2. In next part we will see Struts2 Ajax Example.


1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 、4下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。、可私 6信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 、4下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。、可 6私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 、4下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。、可私 6信博主看论文后选择购买源代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值