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

前端 未结 8 2044
情深已故
情深已故 2020-12-24 13:18

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.

&         


        
相关标签:
8条回答
  • 2020-12-24 13:57

    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.

    0 讨论(0)
  • 2020-12-24 14:04

    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

    0 讨论(0)
  • 2020-12-24 14:05

    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 讨论(0)
  • 2020-12-24 14:06

    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
    
    0 讨论(0)
  • 2020-12-24 14:07
    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 讨论(0)
  • 2020-12-24 14:08

    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">
    
    0 讨论(0)
提交回复
热议问题