Wednesday, 2 January 2013

Struts 2 File Upload & Save Example

Free Domain Name


Let us see how to work with file uploads in struts 2 frame work, things to remember while working with this type of application
  • See in index.jsp i have taken <s:file  name=”uploadFile” i mean my file tag name is uploadFile
  • We used to write setters, getters for this property in Action class right, but while writing we need to write setters, getters for 2 more properties with names uploadFileFileName  &  uploadFileContentType
  • I mean name format must be [ our file property name ]ContentType & [ our file property name ]FileName
  • Actually at run time struts 2 container will injects the required file details into these properties, and thing is see struts.xml -  line 23 fileUpload is the predefined interceptor class, this will take cares every thing
  • Once file uploaded, struts 2 will stores the file with some temp name, its our responsibility to convert and save that file,  see line numbers 39,40,41,42 in Action class of LogingEx.java

File Upload Example

required files….
  • index.jsp
  • success.jsp
  • web.xml
  • struts.xml
  • LogingEx.java

Directory Structure

index.jsp

1
2
3
4
5
6
7
8
9
10
11
12
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<s:head />
</head>
 
<s:actionerror />
 
<s:form action="uploadAction" method="POST" enctype="multipart/form-data">
   <s:file name="uploadFile" label="Choose File" size="40" />
   <s:submit value="Upload" name="submit" />
</s:form>

success.jsp

1
2
3
4
5
6
7
8
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
 
   File uploaded successfully...!!!
 
   File Name : <s:property value="uploadFileFileName"/> <br>
   Content Type : <s:property value="uploadFileContentType"/> <br>
   Temp File Name : <s:property value="uploadFile"/>

LogingEx.java

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
58
59
60
61
package java4s;
import java.io.File;
 
import org.apache.commons.io.FileUtils;
 
import com.opensymphony.xwork2.ActionSupport;
 
public class LogingEx extends ActionSupport{
    private static final long serialVersionUID = 1L;
 
    private File uploadFile;
    private String uploadFileContentType;
    private String uploadFileFileName; 
 
    public File getUploadFile() {
        return uploadFile;
    }
    public void setUploadFile(File uploadFile) {
        this.uploadFile = uploadFile;
    }
 
    public String getUploadFileContentType() {
        return uploadFileContentType;
    }
    public void setUploadFileContentType(String uploadFileContentType) {
        this.uploadFileContentType = uploadFileContentType;
    }
 
    public String getUploadFileFileName() {
        return uploadFileFileName;
    }
    public void setUploadFileFileName(String uploadFileFileName) {
        this.uploadFileFileName = uploadFileFileName;
    }
 
    public String execute()
    {
        try{
        String filePath = "c:/Myuploads"// Path where uploaded file will be stored
        System.out.println("Server path:" + filePath); // check your path in console
        File fileToCreate = new File(filePath, uploadFileFileName);// Create file name  same as original
        FileUtils.copyFile(uploadFile, fileToCreate); // Just copy temp file content tos this file     
 
        }catch(Exception e)
        {
            e.printStackTrace();
            addActionError(e.getMessage());
            return INPUT;
 
        }
        return SUCCESS;
    }
 
}
// Context pirnt.....
 
//private HttpServletRequest servletRequest;
//String filePath = servletRequest.getSession().getServletContext().getRealPath("/");
//System.out.println("Server path:" + filePath);
//File fileN = new File(filePath, this.uploadFileFileName);
//FileUtils.copyFile(this.userImage, fileToCreate);

web.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
xml version="1.0" encoding="UTF-8"?>
  <filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

struts.xml

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
xml version="1.0" encoding="UTF-8"?>
 
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
 
<struts>
    <include file="struts-default.xml"/>
    <package name="a" extends="struts-default">
 
        <action name="uploadAction" class="java4s.LogingEx">
 
            <interceptor-ref name="exception" />
            <interceptor-ref name="alias" />
            <interceptor-ref name="servletConfig" />
            <interceptor-ref name="prepare" />
            <interceptor-ref name="i18n" />
            <interceptor-ref name="chain" />
            <interceptor-ref name="debugging" />
            <interceptor-ref name="profiling" />
            <interceptor-ref name="scopedModelDriven" />
            <interceptor-ref name="modelDriven" />
            <interceptor-ref name="fileUpload">
            <param name="maximumSize">10240</param>
            <param name="allowedTypes">text/plain</param>
            </interceptor-ref>
            <interceptor-ref name="checkbox" />
            <interceptor-ref name="staticParams" />
            <interceptor-ref name="actionMappingParams" />
            <interceptor-ref name="params">
            <param name="excludeParams"> dojo\..*,^struts\..*</param>
            </interceptor-ref>
            <interceptor-ref name="conversionError" />
            <interceptor-ref name="validation">
            <param name="excludeMethods"> input,back,cancel,browse</param>
            </interceptor-ref>
            <interceptor-ref name="workflow">
            <param name="excludeMethods"> input,back,cancel,browse</param>
            </interceptor-ref>
 
            <result name="success">/success.jsp</result>
            <result name="input">/index.jsp</result>
        </action>
    </package>
</struts>

Output

Output If if we take wrong file

Output If file accepted


No comments:

Post a Comment