【问题标题】:How to make input type= file Should accept only pdf and xls如何使输入类型 = 文件应该只接受 pdf 和 xls
【发布时间】:2012-08-21 23:22:21
【问题描述】:

我用<input type= "file" name="Upload" >

现在我想通过只接受 .pdf 和 .xls 文件来限制这一点。

当我单击提交按钮时,它应该验证这一点。

当我点击网页上的文件 (PDF/XLS) 时,它应该会自动打开。

有人可以举一些例子吗?

【问题讨论】:

    标签: html forms


    【解决方案1】:

    您可以通过使用属性accept 并为其添加允许的mime-types 来做到这一点。但并非所有浏览器都尊重该属性,并且可以通过某些代码检查器轻松删除它。因此,无论哪种情况,您都需要检查服务器端的文件类型(您的第二个问题)。

    例子:

    <input type="file" name="upload" accept="application/pdf,application/vnd.ms-excel" />
    

    对于您的第三个问题“当我点击网页上的文件 (PDF/XLS) 时,它应该会自动打开。”:

    你无法做到这一点。如何在客户端计算机上打开 PDF 或 XLS 由用户设置。

    【讨论】:

    • 嗨,feeela 当我上传文件时,它将存储在服务器中。我听说可以通过javascript函数通过单击浏览器上的文件来打开.pdf和.xls文件......
    • 就是这样!双方客户端和服务器解释。很好的答案
    • 如果您在选择框中列出所有文件。您仍然可以上传任何文件。
    【解决方案2】:

    如果您希望文件上传控件限制用户可以通过单击按钮上传的文件类型,那么这就是方式..

    <script type="text/JavaScript">
    <!-- Begin
    function TestFileType( fileName, fileTypes ) {
    if (!fileName) return;
    
    dots = fileName.split(".")
    //get the part AFTER the LAST period.
    fileType = "." + dots[dots.length-1];
    
    return (fileTypes.join(".").indexOf(fileType) != -1) ?
    alert('That file is OK!') : 
    alert("Please only upload files that end in types: \n\n" + (fileTypes.join(" .")) + "\n\nPlease select a new file and try again.");
    }
    // -->
    </script>
    

    然后,您可以从上述按钮的 onClick 之类的事件中调用该函数,如下所示:

    onClick="TestFileType(this.form.uploadfile.value, ['gif', 'jpg', 'png', 'jpeg']);"

    您可以将其更改为:PDFXLS

    你可以在这里看到它的实现:Demo

    【讨论】:

    • 感谢 Vishal Suthar。我认为这个逻辑肯定会帮助我前进。
    • 我很高兴..它肯定会有所帮助,但仍然没有投票..??@Manikandan
    • 我还有一个疑问。我试图在输入类型=文件中限制文件(仅限 PDF&Xls.xlsx)。但它在 Google Chrome 中运行良好。但我无法在 IE 中执行此操作。是否有任何解决方案可以限制 IE 中的文件?如果是,请让我以正确的方式前进。
    • 我刚刚在 IE 中检查了 (codestore.net/store.nsf/unid/DOMM-4Q8H9E),它运行良好..@Manikandan
    • accept-attribute 相比,此方法在本地计算机上选择文件时不会将文件夹内容缩小到选定的文件类型。
    【解决方案3】:

    虽然这个特定示例是针对多文件上传的,但它提供了需要的一般信息:

    https://developer.mozilla.org/en-US/docs/DOM/File.type

    至于在 /download/ 上对文件进行操作,这不是 Javascript 问题——而是服务器配置。如果用户没有安装任何东西来打开 PDF 或 XLS 文件,他们唯一的选择就是下载它们。

    【讨论】:

      【解决方案4】:

      不幸的是,在选择时没有保证方法。

      一些浏览器支持input标签的accept属性。这是一个好的开始,但不能完全依赖。

      <input type="file" name="pic" id="pic" accept="image/gif, image/jpeg" />
      

      您可以使用cfinput 并运行验证以在提交时检查文件扩展名,但不能检查mime 类型。这更好,但仍然不是万无一失的。 OSX 上的文件通常没有文件扩展名,否则用户可能会恶意错误地标记文件类型。

      ColdFusion 的 cffile 可以使用结果 (cffile.contentType) 的 contentType 属性检查 mime 类型,但这只能在上传后完成。这是您最好的选择,但仍然不是 100% 安全,因为 mime 类型仍然可能是错误的。

      【讨论】:

      • 请永远不要根据扩展名检查文件。那么名为 lolcat.jpg 的可执行文件呢?
      • 我认为 phantom42 在这里想说的是您应该检查服务器上的扩展名和 MIME 类型。 input 标签上的 accept 属性可以添加,但不是 100% 有效。
      • 我 100% 同意。不能依赖它,但我发现它可以作为与 cffile.contenttype 一起使用的第一道防线。
      • Hi Phantom 正如您所说,此接受仅适用于 chrome,不适用于 IE。有没有其他方法可以做到这一点,所有浏览器都支持
      • 很遗憾,没有;这就是为什么我说它不能依赖它,如果你使用它,必须与其他方法结合使用。
      【解决方案5】:

      我会过滤服务器端的文件,因为有一些工具,例如 Firefox 上的 Live HTTP Headers,可以上传任何文件,包括 shell。人们可能会入侵您的网站。为了安全起见,做服务器站点。

      【讨论】:

      • 这是真的!请不要忽视这条建议
      【解决方案6】:

      您可以使用 JavaScript。考虑到使用 JavaScript 执行此操作的最大问题是重置输入文件。好吧,这仅限于 JPG(对于 PDF,您必须更改 mime typemagic number):

      <form id="form-id">
        <input type="file" id="input-id" accept="image/jpeg"/>
      </form>
      
      <script type="text/javascript">
          $(function(){
              $("#input-id").on('change', function(event) {
                  var file = event.target.files[0];
                  if(file.size>=2*1024*1024) {
                      alert("JPG images of maximum 2MB");
                      $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                      return;
                  }
      
                  if(!file.type.match('image/jp.*')) {
                      alert("only JPG images");
                      $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                      return;
                  }
      
                  var fileReader = new FileReader();
                  fileReader.onload = function(e) {
                      var int32View = new Uint8Array(e.target.result);
                      //verify the magic number
                      // for JPG is 0xFF 0xD8 0xFF 0xE0 (see https://en.wikipedia.org/wiki/List_of_file_signatures)
                      if(int32View.length>4 && int32View[0]==0xFF && int32View[1]==0xD8 && int32View[2]==0xFF && int32View[3]==0xE0) {
                          alert("ok!");
                      } else {
                          alert("only valid JPG images");
                          $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                          return;
                      }
                  };
                  fileReader.readAsArrayBuffer(file);
              });
          });
      </script>
      

      考虑到这是在最新版本的 Firefox 和 Chrome 以及 IExplore 10 上测试的。

      For a complete list of mime types see Wikipedia.

      For a complete list of magic number see Wikipedia.

      【讨论】:

        【解决方案7】:

        你可以用这个:

        HTML

        <input name="userfile" type="file" accept="application/pdf, application/vnd.ms-excel" />
        

        仅支持 .PDF 和 .XLS 文件

        【讨论】:

          【解决方案8】:

          您可以尝试以下方式

          <input type= "file" name="Upload" accept = "application/pdf,.csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel">
          

          OR(在 asp.net mvc 中)

          @Html.TextBoxFor(x => x.FileName, new { @id = "doc", @type = "file", @accept = "application/pdf,.csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" })
          

          【讨论】:

            【解决方案9】:

            试试这个:-

                          <MyTextField
                            id="originalFileName"
                            type="file"
                            inputProps={{ accept: '.xlsx, .xls, .pdf' }}
                            required
                            label="Document"
                            name="originalFileName"
                            onChange={e => this.handleFileRead(e)}
                            size="small"
                            variant="standard"
                          />
            

            【讨论】:

              猜你喜欢
              • 2019-02-02
              • 2010-12-05
              • 1970-01-01
              • 2017-07-17
              • 2013-03-03
              • 2019-12-05
              • 2022-11-24
              • 2023-04-07
              • 1970-01-01
              相关资源
              最近更新 更多