30

我在 href 点击时触发文件上传。
我试图阻止除 doc、docx 和 pdf 之外的所有扩展名。
我没有得到正确的警报值。

<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 ..它显示错误

4

10 回答 10

74

您可以使用

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

小麦

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

反而。

[编辑] 请注意,.dot也可能匹配。

于 2013-08-01T11:27:03.733 回答
19

最好在输入字段上使用change事件。

更新来源:

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);
   }
});

更新了 jsFiddle

于 2013-08-01T11:20:47.760 回答
6

对于仅在资源管理器窗口中接受扩展名为 doc 和 docx 的文件,请尝试此操作

    <input type="file" id="docpicker"
  accept=".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document">
于 2019-02-06T00:09:15.333 回答
3

下面的代码对我有用:

<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
于 2018-01-16T03:39:17.870 回答
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}
于 2013-08-01T11:31:14.890 回答
0

尝试这个

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

希望它会有所帮助

于 2013-08-01T11:21:38.340 回答
0

您可以通过 REGEX 简单地制作它:

形式:

<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>

和java脚本验证:

<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>

干杯!

于 2017-07-21T08:49:23.653 回答
0

HTML 代码:

<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"/>

反应代码 - 附加文件并将文件设置为状态:

     @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);
  }
于 2022-02-03T12:21:43.300 回答
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 ";
}
});

于 2016-11-14T05:05:51.097 回答
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"}
        }
    }
于 2022-01-06T11:20:07.850 回答