Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow only pdf, doc, docx format for file upload?

I am triggering a file upload on href click.
I am trying to block all extension except doc, docx and pdf.
I am not getting the correct alert value.

<div class="cv"> Would you like to attach you CV? <a href="" id="resume_link">Click here</a></div>     <input type="file" id="resume" style="visibility: hidden"> 

Javascript:

        var myfile="";         $('#resume_link').click(function() {             $('#resume').trigger('click');             myfile=$('#resume').val();             var ext = myfile.split('.').pop();             //var extension = myfile.substr( (myfile.lastIndexOf('.') +1) );              if(ext=="pdf" || ext=="docx" || ext=="doc"){                 alert(ext);             }             else{                 alert(ext);             }          }) 

MyFiddle..its showing error

like image 539
HIRA THAKUR Avatar asked Aug 01 '13 11:08

HIRA THAKUR


People also ask

How do I change the file types in the upload field?

Click on the gear icon to the right of the File upload field to open the File Upload Properties panel. Go to the Options tab. Enter the allowed file extensions in the File Types field.

How do I make a file supported to upload?

If you try to upload a file that is not in the legal extensions you will receive this error. Go to Content > Media Manager > Options. Edit the Legal Extensions (File Types) field to include your desired file extension. Save & Close the changes.

How do I accept a PDF input?

Just insert an onclick attribute on your submit button and call the code that will test the input file value. If the extension is forbidden, you'll have to return false to invalidate the form.


2 Answers

You can use

<input name="Upload Saved Replay" type="file"    accept="application/pdf,application/msword,   application/vnd.openxmlformats-officedocument.wordprocessingml.document"/> 

whearat

  • application/pdf means .pdf
  • application/msword means .doc
  • application/vnd.openxmlformats-officedocument.wordprocessingml.document means .docx

instead.

[EDIT] Be warned, .dot might match too.

like image 123
Grim Avatar answered Oct 05 '22 21:10

Grim


Better to use change event on input field.

Updated source:

var myfile="";  $('#resume_link').click(function( e ) {     e.preventDefault();     $('#resume').trigger('click'); });  $('#resume').on( 'change', function() {    myfile= $( this ).val();    var ext = myfile.split('.').pop();    if(ext=="pdf" || ext=="docx" || ext=="doc"){        alert(ext);    } else{        alert(ext);    } }); 

Updated jsFiddle.

like image 36
antyrat Avatar answered Oct 05 '22 21:10

antyrat