Wednesday, August 21, 2013

Check Valid extension of file at client side while uploding file

This following example allow to user upload only pdf file.for this example we need the jquery.js file.
<html>
<head>
<script src="jquery.js"></script>
<style>
body {
    margin:1em;
    font-size:.9em;
}
h1 {
    margin:1em 0;
    font-weight:bold;
}
h1:not(:first-of-type) {
    border-top:1px solid #ccc;
    padding:1em 0 0;
}
p {
    margin:1em 0;
}
p label {
    color:#333;
    font-family:sans-serif;
    display:inline-block;
    padding:.1em .1em .1em .3em;
    background:#f7f7f7;
    border:1px solid #ccc;
}
aside {
    margin-top:-.5em;
}
aside p {
    color:#333;
    font-size:.8em;
    font-family:sans-serif;
}

</style>
<script>
function getExtension(filename)
{

    var parts = filename.split('.');
    return parts[parts.length - 1];
}

function isPDF(filename)
{
    var ext = getExtension(filename);
    switch (ext.toLowerCase())
    {
    case 'pdf':
   
        /*
        etc
        like
        'xsl'
        */
        return true;
    }
    return false;
}

function failValidation(msg)
{
            alert(msg);
            return false;
}
function validate()
{      
        var file = $('#file');    
       
        if (!isPDF(file.val()))
        {
            return failValidation('Please select a valid file');
        }
               
        // indicate success with alert for now
        alert('Valid file');
        return true;
 }

</script>
</head>
<body>

<form name="frmpdf" action="connect.jsp" onsubmit="return validate()">
<h1>Match all pdf  files (application/pdf)</h1>
<p><label>Pdf File <input type="file" id="file" accept="application/pdf"></label></p>
<input type="submit" value="submit">
</form>
</body>
</html>

for checking image you can write following function.

function isImage(filename) 
 {
    var ext = getExtension(filename);
    switch (ext.toLowerCase()) 
   {
    case 'jpg':
    case 'gif':
    case 'bmp':
        //etc
        return true;
    }
    return false;
}