How do I submit a “file” input without submit button using JavaScript?

前端 未结 5 1626
栀梦
栀梦 2020-12-29 02:27

There is a way to automatically submit a form without clicking to a \"submit\" button?

I have a form with one \"file\" input. I would submit the form after the user

相关标签:
5条回答
  • 2020-12-29 03:00

    yes, you can use the form.submit() function. Add an onchange listener on the file input and link it to the form.submit() function, like so:

    <form action="upload.php" method="post" enctype="multipart/form-data">
    <input type="file" onchange="this.form.submit()" name="myFile"/>
    </form>
    
    0 讨论(0)
  • 2020-12-29 03:00

    This solution works for me.

    <form enctype="multipart/form-data" method="POST" action="/upload">
      <input id="myfilefield" type="file" name="file">
      <input type="submit">
    </form>
    

     

    document.getElementById('myfilefield').onchange = function() {
      this.form.submit();
    };
    

    By the way, you don't need to use flash. Gmail do it by XHR Level 2.

    0 讨论(0)
  • 2020-12-29 03:05

    Yes, you can add the following to the onchange event of the file input:

    <input type='file' .... onchange='this.form.submit();'>
    

    this submits the form right after the user has picked a file. However, the user can't correct a mistaken selection before submitting - be sure to check whether this is really wise.

    0 讨论(0)
  • 2020-12-29 03:10

    I'm not sure what the restrictions are with doing this in an HTML form.

    You can, however, do it with Flash. Gmail does it - when I click "Attach a file", I get prompted with a file browse dialog, and when I OK that dialog the upload begins immediately, and also gives me a progress bar.

    Googling for "Flash uploader" will give you many options, but I don't have experience with any of them.

    0 讨论(0)
  • 2020-12-29 03:16

    I don't believe you can do this. Browsers are very, very strict about what you can do to file upload fields, because of the potential for abuse. If the user accidentally selects a private file, they wouldn't want it to immediately start uploading that file to a random server.

    0 讨论(0)
提交回复
热议问题