Struts2 File Upload to Desire Folder Location

Lets starts with action class, I have created the action class named “WebAction“,

public class WebAction extends ActionSupport {

    private File myfile;
    private String myfileFileName;
    private String myfileContentType;
    private String filePathToSaveInDB;

    public String openHome() {
        return "open";
    }

    public String uploadFileToMyFolder() {
        try {
            ServletContext servletContext = ServletActionContext.getServletContext();
            String path = "MyFolder/";
            //getting the path to where the images will be uploaded
            String filePath = servletContext.getRealPath(path);

            File uploadDir = new File(filePath);
            //if the folder does not exits, creating it
            if (uploadDir.exists() == false) {
                uploadDir.mkdirs();
            }
            setFilePathToSaveInDB(path + "/" + myfileFileName);
            FileUtils.copyFile(myfile, new File(uploadDir, myfileFileName));
          
        } catch (Exception e) {
            System.out.println("Exception : " + e);
            addActionError(e.getMessage());
            return "failure";
        }
        return "success";
    }

// GETTER AND SETTER GOES HERE


In Above “WebAction” action we have
private File myfile: This contains the content of the uploaded file.
private String myfileFileName: The mime type of the uploaded file . (Optional)
private String myfileContentType: This is actual file name of the uploaded file. (Optional)
private String filePathToSaveInDB; It contains path of the image which we use to display the image. (also can be stored in db to be used in latter use)

Now struts.xml consists of

<action name="uploadFileToMyFolder" method="uploadFileToMyFolder" class="com.debraj.WebAction">
            <interceptor-ref name="fileUpload">
                <param name="maximumSize">2097152</param>
                <param name="allowedTypes">
                              image/png,image/gif,image/jpeg,image/jpg
                </param>
            </interceptor-ref>
            <interceptor-ref name="defaultStack"></interceptor-ref>
            <result name="success">/pages/web/Success.jsp</result>
            <result name="failure">/pages/web/failure.jsp</result>
</action>

Two parameter, “maximumSize” and “allowedTypes” are added to the interceptor. “allowedTypes” parameter specifies the content type of the file to be upload i.e “text/plain” specifies uploaded file will be a text file. “maximumSize” parameter set the size of the file to be uploaded, by default the size is 2Mb, but we can increase the upload size limit by adding a single line of code in struts.xml i.e.

<constant name="struts.multipart.maxSize" value="2147483648" />

Struts2 default.properties defines setting to upload file i.e.
“struts.multipart.parser=jakarta/pell” (is used by the fileUpload interceptor to handle HTTP POST requests)
“struts.multipart.maxSize=2097152” (to specify the size of the file)
“struts.multipart.saveDir=” (location to where the file will be saved)

Now Home.jps

<!DOCTYPE HTML>

<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
    <head>
        <title><s:text name="Struts2 File Upload" /></title>
    </head>
    <body>
        <div>
            <s:form id="uploadFileToMyFolder" name="uploadFileToMyFolder" action="uploadFileToMyFolder" enctype="multipart/form-data">
                <s:text name="Upload Image : " />
                <s:file name="myfile" id="myfile"/>
                <s:submit name="submit"/>
            </s:form>
        </div>
    </body>
</html>

Success.jsp

<!DOCTYPE HTML>

<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
    <head>
        <title><s:text name="Struts2 File Upload Success" /></title>
    </head>
    <body>
        <div>
            <s:actionmessage />
            <s:property value="myfile"/><br />
            <s:property value="myfileFileName"/><br />
            <s:property value="myfileContentType"/><br />
            <img src="<s:text name='%{filePathToSaveInDB}'/>"/><br />
            
        </div>
    </body>
</html>

failure.jsp

<!DOCTYPE HTML>

<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
    <head>
        <title><s:text name="Struts2 File Upload Failure" /></title>
    </head>
    <body>
        <div>
            <s:actionerror />
        </div>
    </body>
</html>

That’s all. If you need to display that how many bytes the file has, then in WebAction action just add the below lines of code

String fileSize = FileUtils.byteCountToDisplaySize(logofile.length());

All the uploading files are saved into a temporary directory (by the framework) before being passed in to an Action. Error message like “struts.messages.error.uploading”, “struts.messages.error.file.too.large” and “struts.messages.error.content.type.not.allowed” specifies error while uploading files, size of the file exceeds the maximumSize and content type of the file is doesn’t match with the specified allowedTypes respectively. Actually fileUpload interceptor does the validation.

There are other methods also for uploading file in struts2. This is my approach of file uploading.
Enjoy.

10 responses to this post.

  1. Posted by Amar on August 27, 2011 at 7:01 pm

    But I need it to implement on struts 1.1. Is it possible to do so?

    Reply

  2. Posted by Marganda on September 12, 2011 at 9:45 am

    Thanks , really help me..^^

    Reply

  3. Posted by Mohan on March 9, 2012 at 3:46 pm

    Can you please explain how to add syntax highlighter to blog. I tried it but it’s applying css properly? Thanks.

    Reply

  4. Posted by swarnim prabhat on May 14, 2012 at 11:51 am

    I have to use the same concept using list. How should i do?

    Reply

  5. please tell me how to add datetimestamp to filename while uploading the file .?????

    am using file upload interceptor in struts2 frame work, java1.6

    Reply

    • To add date timestamp :
      YourFileName = YourFileName + new Timestamp(new java.util.Date().getTime());
      please refer to http://docs.oracle.com/javase/6/docs/api/java/sql/Timestamp.html

      Reply

      • i need to save as datetimestamp.”extension of file” not by appending it

      • Posted by Amarendra on March 23, 2017 at 5:58 pm

        Dear Debraj Mallick ,

        I’m facing a problem at the time of up[loading file and save file in struts2.
        I upload multiple File but file name will be change like this upload_65fc954c_15afab7f4e7__8000_00000042.pdf i have converted .tmp to .pdf but i want actual file which i have uploaded at the time of uploading the file.
        I have also set the struts.xml file

        20971527
        application/pdf

        /scannerOcr/scannerSetting.jsp

        Please suggest me how to resolve the problem.

      • Hi,

        Use FileUtils.copyFile to copy the file that you want.

        i have declared a String i.e. ‘myfileFileName’ for this purpose and don’t forget to write the getter & setter methods.

        Good luck.

Leave a comment