how to check if a file is selected using javascript?

后端 未结 3 1299
情深已故
情深已故 2021-01-18 05:11

In php this is how you would check if a file is selected:

$_FILES[\'item\'][\'size\']>0

what about in JavaScript?

I need to know

相关标签:
3条回答
  • 2021-01-18 05:34

    http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-49531485 says:

    value of type DOMString
    When the type attribute of the element has the value "text", "file" or "password", this represents the current contents of the corresponding form control, in an interactive user agent.

    <html>
      <head><title>...</title>
        <script type="text/javascript">
          function foo() {
            var f = document.getElementById("f1");
            alert( ""==f.value ? "nothing selected" : "file selected");
          }
        </script>
      </head>
      <body>
        <form>
          <div>
            <input id ="f1" type="file" name="x" />
          </div>
        </form>
        <button onclick="foo()">click</button>
      </body>
    </html>
    
    0 讨论(0)
  • 2021-01-18 05:34

    I use this javascript:

    var file_selected = false;
    function showNoFile() {
        if(!file_selected) { alert('No file selected!'); } // or anything else
    }
    

    with this html for the file button:

    <input type='file' onchange="file_selected = true;" ...>
    ....
    <input type='submit' onclick='showNoFile();'>
    

    hope that helps!

    0 讨论(0)
  • 2021-01-18 05:42

    So lets say you have some html form and you have a custom file upload input:

    <label for="imageUploadButton">
    <span class="btn" style="padding-left: 10px;">Click here for uploading a new picture</span>
    </label> 
    <input type="file" name="avatar_picture" accept="image/gif,image/jpeg,image/png" id="imageUploadButton" style="visibility: hidden; position: absolute;">
    

    And you want to check the filename of the file the user has chosen/selected:

    Using jquery

    <script type="text/javascript">
      $(function() {
         $("input:file").change(function (){
           var fileName = $(this).val();
           alert(fileName); //Do with the filename whatever you want
         });
      });
    </script>
    

    @https://stackoverflow.com/a/5670938/2979938

    For those using requireJS:

    $("input:file").change(function () {
      var fileName = $(this).val();
      alert(fileName); //Do with the filename whatever you want
    });
    
    0 讨论(0)
提交回复
热议问题