34

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

Lii
  • 11,553
  • 8
  • 64
  • 88
HIRA THAKUR
  • 17,189
  • 14
  • 56
  • 87

11 Answers11

83

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.

SUB0DH
  • 5,130
  • 4
  • 29
  • 46
Grim
  • 1,938
  • 10
  • 56
  • 123
  • will this accept doc and docx...and i dont need to write any validation for this? – HIRA THAKUR Aug 01 '13 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 01 '13 at 11:33
  • Safari and IE9 and older dont support this attribute. I suspect IE10 doesn't either but I can't remember specifically. – Ray Nicholus Aug 01 '13 at 11:55
  • http://www.w3schools.com/TAGS/att_input_accept.asp sais ie10 accept. You are right, ie9 doesnt accept. – Grim Aug 01 '13 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 – dont_trust_me Jul 19 '18 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.

antyrat
  • 27,479
  • 9
  • 75
  • 76
7

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">
Andres9619
  • 184
  • 2
  • 4
  • 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 06 '19 at 09: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
satish
  • 157
  • 1
  • 2
  • 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 05 '19 at 09:25
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}
Gan
  • 624
  • 1
  • 10
  • 31
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!

Adam Kozlowski
  • 5,606
  • 2
  • 32
  • 51
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"}
        }
    }
cigien
  • 57,834
  • 11
  • 73
  • 112
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);
  }
Nimantha
  • 6,405
  • 6
  • 28
  • 69
-1

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

Sonu Sindhu
  • 1,752
  • 15
  • 25
-1

$('#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 ";
}
});
  • Why did you just copy/paste this [answer](https://stackoverflow.com/a/40582186/446594)? – DarkBee Jul 24 '23 at 08:17
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 26 '23 at 19:11
-2

$('#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 ";
}
});
ipul
  • 1