Search code examples
validationfile-uploadstruts-1apache-commons-fileupload

file upload validation in Struts


This is my upload page for which i need to validate. Currently the validation is not happening.I think in Struts 2 form validation is different. Can I follow this link http://www.mkyong.com/struts/struts-validator-framework-example/ and implement my form in a similar way?

<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%>
<%@ taglib uri="/WEB-INF/displaytag-12.tld" prefix="display"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%-- <%@ taglib prefix="s" uri="/struts-tags"%> --%>
<%@ page errorPage="error.jsp"%>

</style>
<script>
    var _validFileExtensions = [".xlsx", ".xls", ".xlt"]; 
    function Validate(oForm) {
        alert("alert message in upload form");
    if( document.getElementById("filename").files.length == 0 ){
        alert("inside if");
         document.getElementById("fileSelect").style.display=""; 
        return false;
    }
    else{
        alert("inside else");
        document.getElementById("fileSelect").style.display="none"; 

    }
    var arrInputs = oForm.getElementsByTagName("input");
    for (var i = 0; i < arrInputs.length; i++) {
        var oInput = arrInputs[i];
        if (oInput.type == "file") {
            var sFileName = oInput.value;
            if (sFileName.length > 0) {
                var blnValid = false;
                for (var j = 0; j < _validFileExtensions.length; j++) {
                    var sCurExtension = _validFileExtensions[j];
                    if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
                        blnValid = true;
                        break;
                    }
                }

                if (!blnValid) {
                    alert("not valid");
                    document.getElementById("fileFormat").style.display="";
                    return false;
                }
            }
        }
    }

    return true;
}  



</script>
<center> 
    <html:form action="/process.do?method=upload" method="POST" enctype="multipart/form-data" onsubmit="return Validate(this);">
        <table cellpadding='4' border='0' width="80%">
                <tr>
                    <td width="1%"></td>
                    <td colspan='4' align='center'>
                        <b>Upload VIP Orders Shipment Dates:</b>
                        <div style="margin: 20px 20px 20px 250px">


                         <strong><label>File :</label></strong>&nbsp; &nbsp; &nbsp; <html:file id="filename" property="uploadedFile"/><br/>
                        <input type="submit" value="Upload File" style="margin: 40px 0 0 160px"/><br /><br />
                        <div id="fileSelect" style="color:Red;display:none">No file selected for uploading.</div>
                        <div id="fileFormat" style="color:Red;display:none">Invalid File Format. Only .xlsx, .xls, and .xlt file format allowed.</div>

                        </div>
                    </td>
                </tr>
        </table>
    </html:form> 

I just want to grab the filename. If filename is null then display error msg.

I want the validation to happen on the client side itself instead of the request going to server side for validation. These are the two messages i want to display: No file selected for uploading ----- when without select file you click on submit button. and Invalid File Format. Only .xlsx, .xls, and .xlt file format allowed--- when file is not in excel format


Solution

  • I found out the way:

    jsp page:

    function performAction(obj){        
        var aForm = document.forms[0];  
        var formAction = aForm.action;
        formAction = formAction.substring(0,formAction.indexOf('?'));
        if(obj == 'LOADFILE'){          
        aForm.action = formAction+'?method=loadFile';
    }
    
                if(obj == 'UPLOADFILE'){            
                aForm.action = formAction+'?method=upload';
                }
    
              aForm.submit();
    
    }
    
    </script>
    
    <html:form action="/process.do?method=upload" method="post" enctype="multipart/form-data">
         <table>
         <tr>                                                               
            <b> Please download the template file by 
            <A href="#" onclick="return performAction('LOADFILE')"  >clicking here</A> 
            </b>
    
            <strong><label>File :</label></strong><html:file property="uploadedFile" /><br/>
    
            <INPUT TYPE="submit" value="Upload"  onclick="return performAction('UPLOADFILE')">
    
            </tr>
         </table>
    </html:form> 
    

    bean class:

    public class process  extends ActionForm {
    
        public ActionErrors validate(ActionMapping mapping,
                    HttpServletRequest request) {
    
                ActionErrors errors = null;
    
                if ("upload".equals(request.getParameter(mapping.getParameter()))) {
                    errors = new ActionErrors();
                    if (uploadedFile == null || uploadedFile.getFileSize()==0 ) {
                        errors.add(" ", new ActionMessage("error.file.notselected"));
    
                    }
                    else{
                        if (!uploadedFile.getFileName().contains(".xls")
                                && !uploadedFile.getFileName().contains(".xlsx")) {
                            errors.add(" ", new ActionMessage("error.file.notxlsx"));
                        }
                    }
    
                }
    
                return errors;
            }
    }