0

I'm working in a Rails application and I want to conditionally apply a file upload field based on the existence of a previous input.

In this case if a user tries to upload a PDF file another file field presents itself to upload a placeholder image.

I'm a relative newb with jQuery and thus I have the following that will notice a change affect on the input field.

$("input[type=file]").on('change', function(){
  {alert(this.files[0].name);
  }
})

What I'm struggling with is how to have jQuery parse out and look for pdf files. I'm pretty sure I can figure out appending if PDF present with the form. How do I check the file upload for a specific file type of PDF?

I've also gone so far with:

$("input[type=file]").on('change', function(){
  var fileExtension = 'pdf';
  if ($.contains($(this).val().split('.'), fileExtension) > 0){
    alert('Huzzah');
  }
})

This does nothing. I get no errors but there's no alert when used in the console.

1 Answer 1

3

At minimum you can check the type property as you iterate over the selected files. The type you want to look for PDF's is application/pdf.

For true MIME types you'll want to use FileReader and Blob to evaluate the file(s). But that's another can of worms.

Try selecting a PDF file in this snippet...

$('input[type="file"]').on('change', function() {
  Object.values(this.files).forEach(function(file) {
    console.log(`Type: ${file.type}`);
    if (file.type == 'application/pdf') {
      console.log('Huzzah!')
    }
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="file" multiple>

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

3 Comments

How do i get file.temp_name to move in php? Thanks
I know how to do it, but when I execute the code it tells me that $ _FILES ['temp_name'] not exist :( . What is the correct way to send it to PHP to process it? Thanks
It’s usually found at $_FILES['name_of_your_input']['tmp_name']

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.