3

How can I check the file type (original type) with JQuery? I mean even if I change the file format manually from .pdf to .jpg, I should get .pdf because this file is PDF document not picture. I am using the following code for checking file type :

var fileExtension = ['jpeg', 'jpg', 'png'];
if ($.inArray(file_input.val().split('.').pop().toLowerCase(), fileExtension) == -1) {
  alert("Wrong format!");       
}
else {
  alert("Correct format!");
}
11
  • Possible duplicate of Validation of file extension before uploading file Commented Feb 23, 2016 at 17:04
  • Possible duplicate of Check file type when form submit? Commented Feb 23, 2016 at 17:05
  • i don't have any idea is it possible or not?? But if just need the current file extension then var ext = fileName.split('.').pop(); will be okey. Commented Feb 23, 2016 at 17:06
  • 1
    I think the only reliable way of fetching the mime-type would be on the server so perhaps an AJAX request is necessary to return the mime-type from the server. Commented Feb 23, 2016 at 17:55
  • 1
    @UmidjonUrunov : using jquery itself, you can get the filetype and you can then use it to validate your code, check my answer below or the answer here : stackoverflow.com/questions/18299806/… Commented Feb 23, 2016 at 19:21

1 Answer 1

2

Borrowing the JS from @Drakes answer here.

I've posted the JQuery Implementation for the same below :

$('#show').on("click", function() {
  var files = $("#your-files")[0].files[0];
  var temp = "";
  temp += "<br>Filename: " + files.name;
  temp += "<br>Type: " + files.type;
  temp += "<br>Size: " + files.size + " bytes";
  $('#details').html(temp);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="your-files" multiple>
<button id="show">
  Show Details
</button>
<div id="details">
</div>

You can then use the file type that you get using the above jQuery in the control statements of the code posted in your question.

Sign up to request clarification or add additional context in comments.

4 Comments

OP said that he would like to get file type information without relying on the extension of the file name.
@Stack0verflow : The above snippet gives the correct file type irrespective of the extension of the file name.
It does not when I try it multiple times.
@stark, I changed extension of jar file to .txt means original file is jar but i changed to text file manually so file type should be come jar but is showing only text/plain so its not working. can you update your answer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.