This is 6 of 8 part of struts 2 tutorial.In this tutorial we will learn how to upload file to server in struts 2 and also how save uploaded file on directory of server machine.
Tutorial Content:
1 2 3 4 5 6 7 8 9 10 |
Part-1:<a href="https://www.java2blog.com/2012/07/welcome-to-strut2.html" target="_blank" rel="noopener">Introduction to struts 2</a> Part-2:<a href="https://www.java2blog.com/2012/07/configuring-struts-2.html" target="_blank" rel="noopener">configuring struts 2 in eclipse</a> Part-3:<a href="https://www.java2blog.com/2012/07/hello-world-first-struts-2-project.html" target="_blank" rel="noopener">Struts 2 hello world example</a> Part-4:<a href="https://www.java2blog.com/2012/07/login-page-with-validation-in-struts-2.html" target="_blank" rel="noopener">Login page with validation in struts 2</a> Part-5:<a href="https://www.java2blog.com/2012/07/struts-2-interceptors-with-example.html" target="_blank" rel="noopener">Struts 2 interceptors with example</a> Part-6:<a href="https://www.java2blog.com/2012/07/file-upload-in-struts-2.html" target="_blank" rel="noopener">File upload in struts 2</a> Part-7:<a href="https://www.java2blog.com/2012/08/struts-2-ajax-example.html" target="_blank" rel="noopener">Struts 2 ajax example</a> Part-8:<a href="https://www.java2blog.com/2012/09/struts-2-spring-3-integration-example.html" target="_blank" rel="noopener">Struts 2 spring 3 integration example</a> |
Create project named “fileUploadInStruts2”.For configuring struts 2 in your eclipse ide please refer configuring struts 2 link.Project stucture:
Action class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
package org.arpit.javaPostsForLearning; import java.io.File; import java.io.IOException; 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 toBeUploaded;    private String toBeUploadedFileName;    private String toBeUploadedContentType;    private HttpServletRequest servletRequest;    public String execute()    {        String filePath = servletRequest.getSession().getServletContext().getRealPath("/");         File fileToCreate = new File(filePath, this.toBeUploadedFileName);         try {          FileUtils.copyFile(this.toBeUploaded, fileToCreate);       } catch (IOException e) {          addActionError(e.getMessage());       }       return SUCCESS;    }    public File getToBeUploaded() {       return toBeUploaded;    }    public void setToBeUploaded(File toBeUploaded) {       this.toBeUploaded = toBeUploaded;    }    public String getToBeUploadedFileName() {       return toBeUploadedFileName;    }    public void setToBeUploadedFileName(String toBeUploadedFileName) {       this.toBeUploadedFileName = toBeUploadedFileName;    }    public String getToBeUploadedContentType() {       return toBeUploadedContentType;    }    public void setToBeUploadedContentType(          String toBeUploadedFileNameContentType) {       this.toBeUploadedContentType = toBeUploadedFileNameContentType;    }    @Override    public void setServletRequest(HttpServletRequest servletRequest) {       this.servletRequest=servletRequest;          }    } |
private File toBeUploaded //Actual file to be uploaded
private String toBeUploadedFileName // file name of actual file to be uploaded
private String toVeUploadedContentType // content type of actual file to be uploaded
We have provided getters and setters for above attributes.So struts 2 automatically set these value according to file being uploaded.
For example if your file name is “sampleFile” then struts 2 interceptor add three parameters to request.
Three parameters are:
[sampleFile]:file
[sampleFile]FileName:String
[sampleFile]ContentType:String
you can notice here that we have given our action class attributes in same format so it will automatically set these attributes according to file being uploaded.
One more thing is that we have implemented “ServletRequestAware” interface in our action class
This is to get ServletRequest object.This request object is required to get path of server machine where file is to be uploaded.
JSPs:
fileUpload.jsp:
1 2 3 4 5 6 7 8 9 10 |
 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"    pageEncoding="ISO-8859-1"%> <%@taglib uri="/struts-tags" prefix="s"%> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>file upload page</title> |
We have used tag for file upload interface.
uploadSucceed.jsp:
Create jsp named “uploadSucceed.jsp” under WebContent folder.
Copy following content into uploadSucceed.jsp.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" Â Â Â pageEncoding="ISO-8859-1"%> <%@taglib uri="/struts-tags" prefix="s"%> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Upload Successful</title> File Name : <property value="toBeUploadedFileName"></property> Content type: <property value="toBeUploadedContentType"></property> User file : <property value="toBeUploaded"></property> Uploaded file: "> |
1 2 3 |
Copy following content to struts.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?xml version="1.0" encoding="UTF-8" ?> <struts>    <package name="default" extends="struts-default" namespace="/">       <action name="fileUpload" class="org.arpit.javaPostsForLearning.FileUploadAction">          <interceptor-ref name="fileUpload">             <param name="maximumSize">1048576             <param name="allowedTypes">                image/png,image/gif,image/jpeg,image/pjpeg                 </interceptor-ref>          <interceptor-ref name="defaultStack"></interceptor-ref>          <result name="success">uploadSucceed.jsp</result>          <result name="input">fileUpload.jsp</result>       </action>    </package> </struts> |
Web.xml:
It is same as in previous posts except that we have changed welcome file to “fileUpload.jsp”
Copy following content into web.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?xml version="1.0" encoding="UTF-8" ?> <struts>    <package name="default" extends="struts-default" namespace="/">       <action name="fileUpload" class="org.arpit.javaPostsForLearning.FileUploadAction">          <interceptor-ref name="fileUpload">             <param name="maximumSize">1048576             <param name="allowedTypes">                image/png,image/gif,image/jpeg,image/pjpeg                 </interceptor-ref>          <interceptor-ref name="defaultStack"></interceptor-ref>          <result name="success">uploadSucceed.jsp</result>          <result name="input">fileUpload.jsp</result>       </action>    </package> </struts> |
Run project:
Source code:
1 2 3 4 |
<b>Source:</b><a href="https://dl.dropbox.com/s/r5c172j7ooofi5x/FileUploadInStruts2.7z" target="_blank" rel="noopener">Download without jars files</a> <b>Source + lib</b>: <a href="https://dl.dropbox.com/s/a42yvkg7ndxbqrj/fileUploadInStruts2WithJars.zip" target="_blank" rel="noopener">Download with jars files</a> |
Now in next post,we will write struts 2 ajax example.