Newsletter

Struts 2 File Upload & Save Example

Struts » on Nov 8, 2011 { 22 Comments } By Sivateja

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

<%@ 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

<%@ 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

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

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <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

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<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

 

​​

You Might Also Like

  ::. About the Author .::

Java4s_Author
- Java/J2EE Full Stack Developer
Founder of Java4s - Get It Yourself, A popular Java/J2EE Programming Blog, Love Java and UI frameworks.
You can sign-up for the Email Newsletter for your daily dose of Java tutorials.

Comments

22 Responses to “Struts 2 File Upload & Save Example”
  1. Merlene Standberry says:

    Well I really enjoyed reading it. This article offered by you is very constructive for accurate planning.

  2. saharh says:

    thanks for this.

    but if we want to check that only .txt or .csv is uploaded then how to validate the extension..

  3. Java4s says:

    @Saharh

    Actually in the current example i have given

    <param name=”allowedTypes”>text/plain</param>

    to allow text related files only. When the uploaded file type does not match one of the MIME types specified a field error will be created.

    If that is image, you can give

    <param name=”allowedTypes”>image/jpeg</param>

    [or]

    <param name=”allowedTypes”>image/gif</param>

    its depends.

  4. Bhaskar says:

    Hi,
    I am unable to find to retrieve the uploaded file,the filePath mentioned did not contain any concerned file!

  5. Java4s says:

    @Bhaskar

    You will be able to find your uploaded file in ‘c:/Myuploads‘ location, however you can change the location.

  6. kanishka says:

    this is work how can we upload mp3 file format

  7. prabakaran says:

    could u plz do with oracle database because im facing with oracle db but not with mysql

  8. vaigha says:

    how to save the file in a different extension.Like i can upload both .xls & .xlsx but it should save in .xlsx format only.How can i do that?

  9. Amol Ubale says:

    Nice article to good support to my project for uploading file.

  10. Very useful for me.Thank you so much.

  11. can u please post a tutorial on struts 2 preloaded interface and service locator… Thnx in advance 😛

  12. munna says:

    please reply me how to add datetimestamp to filename while uploading file.?????

  13. niraj says:

    i upload .csv file and i got .tmp file.. so how could i get my original file (.csv).

  14. Pavan says:

    Can you explain a code uploading image to mySQL database using struts2, WITHOUT any tiles or hibernate ingration. Thankyou.

  15. Sudeetha Nuwan says:

    application/vnd.ms-excel use for upload csv and another ms excel related formats.

  16. sankar says:

    very nice examples easy to under stand thank you so much

  17. k says:

    The image uploaded is not accepted..its showing null

  18. Subrahmanyam says:

    File upload interceptor is not working fine in ie if i give valid file format also not accepting

  19. chikku says:

    org.apache.jasper.JasperException: javax.servlet.ServletException: java.lang.NullPointerException

  20. san says:

    Hi, i tried the above one but i’m getting “java.lang.NoSuchMethodError: org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(Lorg/apache/commons/fileupload/RequestContext;)Ljava/util/List;” error so for what reason i’m getting this error i followed all the steps and including jar files.

  21. Amarendra says:

    When i upload the file then that file name will be change into upload_421e7f6a_15acb7b662b__8000_00000013.pdf. my original file name is 0009012199321_000114.pdf.
    I want this file after uploading on this format 9012199321.pdf.

    Please help me how can do that.
    Thanks in advance

  22. Ankit says:

    Hi Sivateja,
    You explained very well but when i upload file (Content-Disposition: form-data; name="uploadedFile"; filename="downloadFile_7.pdf") then filename is not changing when i try to change filename using burpsuit.
    I m trying to implement security for file name and content change.
    —–
    Please look into this problem.

Name*
Mail*
Website



By posting your answer, you agree to our comments policy.
Most Recent Posts from Top Categories
Spring Boot Hibernate Spring
Contact | About Us | Privacy Policy | Advertise With Us

© 2010 - 2018 Java4s - Get It Yourself.
The content is copyrighted to Sivateja Kandula and may not be reproduced on other websites.