33

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

4
  • I don't think that will work in all browsers. If you use HTML5 you can use the attribute accept.
    – putvande
    Aug 1, 2013 at 11:20
  • Your fiddle doesn't work at all for me. You need to close the <input> tag at least.
    – Rup
    Aug 1, 2013 at 11:20
  • @Rup <input> tags are self-closing. Aug 1, 2013 at 11:30
  • Does this answer your question? How to make <input type="file"/> accept only these types?
    – S. Hesam
    May 16, 2020 at 10:51

10 Answers 10

82

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.

5
  • will this accept doc and docx...and i dont need to write any validation for this? Aug 1, 2013 at 11:31
  • See, if the client-os dont know about what is the mime-type of .pdf-files, it won't show .pdf-files for selection! You can use the navigator.mimeType to evaluate this cornercase.
    – Grim
    Aug 1, 2013 at 11:33
  • Safari and IE9 and older dont support this attribute. I suspect IE10 doesn't either but I can't remember specifically. Aug 1, 2013 at 11:55
  • w3schools.com/TAGS/att_input_accept.asp sais ie10 accept. You are right, ie9 doesnt accept.
    – Grim
    Aug 1, 2013 at 11:58
  • 8
    The user can still select "all files" in the explorer window, and then be able to upload whatever file he/she wants. This doesnt validate the format, its just a "starting pont" of what files are visible in the explorer window while selecting a file Jul 19, 2018 at 10:47
21

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.

5
  • no no no...its correct..i just made a mistake while uploading the syntax Aug 1, 2013 at 11:21
  • OK, fair enough. Please either fix your fiddle, or tell us what error you're actually seeing (behaviour and script errors), or both - because it's not currently possible for us to reproduce it.
    – Rup
    Aug 1, 2013 at 11:23
  • my fiddle is not working its showing error {"error": "Please use POST request"}...and i am just not able to get the alert of my extension??there is no syntax error.. Aug 1, 2013 at 11:26
  • @MESSIAH Because of <a> element reloads iframe, so e.preventDefault() fix this problem.
    – antyrat
    Aug 1, 2013 at 11:37
  • If the document were to be renamed with extension in DOCX, this would not work.
    – PCK
    Dec 17, 2019 at 4:14
8

For only acept files with extension doc and docx in the explorer window try this

    <input type="file" id="docpicker"
  accept=".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document">
1
  • 3
    That's just a hint though, not a firm restriction. You can still choose a file with a different extension.in the dialog box.
    – Rup
    Feb 6, 2019 at 9:49
3

Below code worked for me:

<input #fileInput type="file" id="avatar" accept="application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document" />

application/pdf means .pdf
application/msword means .doc
application/vnd.openxmlformats-officedocument.wordprocessingml.document means .docx
1
  • I downvoted. Today, id like to remove my downvote because I know now the meaning of #fileInput. Furthermore I do like to upvote becasue it is indeed helpful and I was wrong in downvote the answer! Unfortuantely I can not upvote the answer nor remove the downvote. Because Your vote is now locked in unless this answer is edited.. In the reality, I do think this answer is helpful.
    – Grim
    Aug 5, 2019 at 9:25
0

Try this

 $('#resume_link').click(function() {
        var ext = $('#resume').val().split(".").pop().toLowerCase();
        if($.inArray(ext, ["doc","pdf",'docx']) == -1) {
            // false
        }else{
            // true
        }
    });

Hope it will help

4
  • Can you highlight what you've changed? Apart from the refactor / rearrange it looks like it's just the toLowerCase()?
    – Rup
    Aug 1, 2013 at 11:25
  • @Rup if($.inArray(ext, ["doc","pdf",'docx']) == -1) looked here Aug 1, 2013 at 11:26
  • did you just ripped it off from other question..i just saw the exact answer on some other question.. Aug 1, 2013 at 11:29
  • @MESSIAH up-vote if you think it help you to solve the problem Aug 1, 2013 at 12:06
0
var file = form.getForm().findField("file").getValue();
var fileLen = file.length;
var lastValue = file.substring(fileLen - 3, fileLen);
if (lastValue == 'doc') {//check same for other file format}
0

$('#surat_lampiran').bind('change', function() {
  alerr = "";
  sts = false;
  alert(this.files[0].type);
  if(this.files[0].type != "application/pdf" && this.files[0].type != "application/msword" && this.files[0].type != "application/vnd.openxmlformats-officedocument.wordprocessingml.document"){
  sts = true;
  alerr += "Jenis file bukan .pdf/.doc/.docx ";
}
});

0

You can simply make it by REGEX:

Form:

<form method="post" action="" enctype="multipart/form-data">
    <div class="uploadExtensionError" style="display: none">Only PDF allowed!</div>
    <input type="file" name="item_file" />
    <input type="submit" id='submit' value="submit"/>
</form>

And java script validation:

<script>
    $('#submit').click(function(event) {
        var val = $('input[type=file]').val().toLowerCase();
        var regex = new RegExp("(.*?)\.(pdf|docx|doc)$");
        if(!(regex.test(val))) {
            $('.uploadExtensionError').show();
            event.preventDefault();
        }
    });
</script>

Cheers!

0
if(req.file){
        let img = req.file ;
       if(img.mimetype != "application/pdf" && img.mimetype != "application/msword" && img.mimetype != "application/vnd.openxmlformats-officedocument.wordprocessingml.document"){
       throw {message :"Please enter only pdf and docx file"}
        }
    }
0

HTML code:

<input type="file" multiple={true} id="file"  onChange={this.addFile.bind(this)} accept="application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,.ppt, .pptx"/>

React code - file attached and set files in state:

     @autobind
      private addFile(event) {
     for(var j=0;j<event.target.files.length;j++){
          var _size = event.target.files[j].size;
          var fSExt = new Array('Bytes', 'KB', 'MB', 'GB'),
          i=0;while(_size>900){_size/=1024;i++;}
          var exactSize = (Math.round(_size*100)/100)+' '+fSExt[i];
          var date = event.target.files[0].lastModifiedDate,
          mnth = ("0" + (date.getMonth() + 1)).slice(-2),
          day = ("0" + date.getDate()).slice(-2);
          date=[day,mnth,date.getFullYear()].join("/");
          fileinformation.push({
            "file_name":  event.target.files[j].name,
            "file_size": exactSize,
            "file_modified_date":date
          });
          var ext = event.target.files[j].name.split('.').pop();
          if(ext=="pdf" || ext=="docx" || ext=="doc"|| ext=="ppt"|| ext=="pptx"){
            
          } else{
            iscorrectfileattached=false;
          }
        }
        if(iscorrectfileattached==false){
          alert("Only PFD, Word and PPT file can be attached.");
          return false;
        }
   this.setState({fileinformation});
    //new code end
    var date = event.target.files[0].lastModifiedDate,
    mnth = ("0" + (date.getMonth() + 1)).slice(-2),
    day = ("0" + date.getDate()).slice(-2);
    date=[day,mnth,date.getFullYear()].join("/");
    this.setState({filesize:exactSize});
    this.setState({filedate:date});
    //let resultFile = document.getElementById('file');
    let resultFile = event.target.files;
    console.log(resultFile);
    let fileInfos = [];
    for (var i = 0; i < resultFile.length; i++) {
      var fileName = resultFile[i].name;
      console.log(fileName);
      var file = resultFile[i];
      var reader = new FileReader();
      reader.onload = (function(file) {
         return function(e) {
              //Push the converted file into array
               fileInfos.push({
                  "name": file.name,
                  "content": e.target.result
                  });
                };
         })(file); 
      reader.readAsArrayBuffer(file);
    }
    this.setState({fileInfos});
    this.setState({FileNameValue:  event.target.files[0].name });
    //this.setState({IsDisabled:  true });//for multiple file

    console.log(fileInfos);
  }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.