Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :)

like image 629
suraj Avatar asked Apr 25 '12 05:04

suraj


2 Answers

To validate a filetype on javascript, here are some ways:

// Your way: getting the extension and checking it.
// I suggest this way instead of using indexOf:
var ext = fileName.split('.').reverse()[0]
// Splits by '.', reverse the array, and returns the first element

// Another way: checking the type of the file
if ( fup.files[0].type === 'application/pdf' ) {
    console.log( 'It is validated!' )
}

Live example: http://jsbin.com/akati3/2 thanks to https://stackoverflow.com/a/4581316/851498

But then, you should really validate this on the server side as others said.

like image 64
Florian Margaine Avatar answered Sep 20 '22 23:09

Florian Margaine


Any kind of javascript validation is only for users comfort. Everything should be validated on serverside too. User can easily disable or modify any javascript code.

Anyway. you can't check file contents in javascript.

In PHP, you can use http://www.php.net/manual/en/function.finfo-file.php to detect file type by it's contents. Most of other languages should have similar functionality.

like image 45
Māris Kiseļovs Avatar answered Sep 19 '22 23:09

Māris Kiseļovs