Posts Tagged ‘mega big fileupload’

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.