【问题标题】:Allow only pdf, doc, docx format for file upload?只允许 pdf、doc、docx 格式的文件上传?
【发布时间】:2013-08-02 06:56:36
【问题描述】:

我在点击 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..显示错误

【问题讨论】:

  • 我认为这不适用于所有浏览器。如果您使用 HTML5,则可以使用属性 accept
  • 你的小提琴对我来说根本不起作用。您至少需要关闭&lt;input&gt; 标签。
  • @Rup &lt;input&gt; 标签是自动关闭的。

标签: javascript jquery


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:
    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"}
            }
        }
    

    【讨论】:

      【解决方案3】:

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

          <input type="file" id="docpicker"
        accept=".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document">
      

      【讨论】:

      • 这只是一个提示,并不是严格的限制。您仍然可以在对话框中选择具有不同扩展名的文件。
      【解决方案4】:

      以下代码对我有用:

      <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
      

      【讨论】:

      • 我投了反对票。今天,我想删除我的反对票,因为我现在知道#fileInput 的含义。此外,我确实喜欢投票,因为它确实很有帮助,而我对答案的投票是错误的!不幸的是,我不能赞成答案,也不能删除反对票。因为Your vote is now locked in unless this answer is edited.。实际上,我确实认为这个答案很有帮助。
      【解决方案5】:

      您可以通过 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>
      

      干杯!

      【讨论】:

        【解决方案6】:

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

        【讨论】:

          【解决方案7】:

          你可以使用

          <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 也可能匹配。

          【讨论】:

          • 这会接受 doc 和 docx...而且我不需要为此编写任何验证吗?
          • 看,如果客户端操作系统不知道.pdf-files 的mime-type 是什么,它就不会显示.pdf-files 供选择!您可以使用navigator.mimeType 来评估这个cornercase。
          • Safari 和 IE9 及更早版本不支持此属性。我怀疑 IE10 也没有,但我记不清了。
          • w3schools.com/TAGS/att_input_accept.asp sais ie10 接受。你说得对,ie9不接受。
          • 用户仍然可以在资源管理器窗口中选择“所有文件”,然后可以上传他/她想要的任何文件。这不会验证格式,它只是选择文件时在资源管理器窗口中可见哪些文件的“起始点”
          【解决方案8】:
          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}
          

          【讨论】:

            【解决方案9】:

            最好在输入字段上使用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

            【讨论】:

            • 不不不......它是正确的......我只是在上传语法时犯了一个错误
            • 好的,很公平。请修复您的小提琴,或告诉我们您实际看到的错误(行为和脚本错误),或两者兼而有之 - 因为我们目前无法重现它。
            • 我的小提琴没有工作它的显示错误{"error": "Please use POST request"}...我只是无法收到我的扩展程序的警报??没有语法错误..
            • @MESSIAH 因为&lt;a&gt;元素重新加载iframe,所以e.preventDefault()修复了这个问题。
            • 如果文档要在 DOCX 中使用扩展名重命名,这将不起作用。
            【解决方案10】:

            试试这个

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

            希望对你有帮助

            【讨论】:

            • 您能突出显示您所做的更改吗?除了重构/重新排列之外,它看起来只是 toLowerCase()?
            • @Rup if($.inArray(ext, ["doc","pdf",'docx']) == -1) 看过这里
            • 你是不是从其他问题上扯下来了……我刚刚看到了其他问题的确切答案……
            • @MESSIAH 如果您认为它可以帮助您解决问题,请投票
            猜你喜欢
            • 2015-06-18
            • 1970-01-01
            • 2013-01-29
            • 1970-01-01
            • 2023-03-24
            • 1970-01-01
            • 1970-01-01
            • 2019-02-27
            • 2015-11-06
            相关资源
            最近更新 更多