Search code examples
javascriptjspfile-uploadfile-format

Validating a pdf file other than its extension in javascript?


I give user the option of uploading a file like this

<form action="#" onsubmit="return Checkfiles(this);">
    <center><input type="file" id="filename"> 
    <input type="submit" value="Go!"></center>
    </form>

When user uploads the file, I validate the file using the following javascript function

<script type="text/javascript">
        function Checkfiles()
        {
        var fup = document.getElementById('filename');
        var fileName = fup.value;
        var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
        if(ext == "pdf" )
        {
        return true;
        } 
        else
        {
        alert("Upload pdf files only");
        fup.focus();
        return false;
        }
        }
    </script>

Evertything is working fine with it.
But I want to validate file by some other means and not just by its extension
I will give reason for doing this. I renamed an image file to image.pdf and now its in pdf format but couldnt be opened.

So I want to validate a pdf file in exact way. Is there any other way to check other than by its extension?
Edit
I want to do validation at server end using jsp page. So what should I do for that?
Thanks in ADVANCE :)


Solution

  • As far as I know, checking if a pdf actually is a pdf can only be done on server side. You could try and open it with IText or something similar; I bet it throws some sort of exception when you try opening or modifying something else then a PDF.