Skip to content
Advertisement

Do modern browsers support onchange=”this.form.submit()” for file upload?

I would like to have an upload form that automatically submits as soon as the user has selected a file.
This question has been asked many times before. If I understood the other threads correctly, this should work:

<form method="post" enctype="multipart/form-data">
  <input id="fileToUpload" onchange="form.submit()" type="file"/>
</form>

<?php 
  if(isset($_FILES["fileToUpload"])){
    echo "You successfully entered a file for the upload!";
    // move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], "uploads/my_image.png");
  }
?> 

When I select a file, I see the file name briefling flashing instead of the “no file chosen”. But $_FILES is not set.

Do modern browsers block onchange="form.submit()" for type="file"?
I tried it with Firefox 68 and Microsoft Edge 84.

Advertisement

Answer

To allow $_FILES to detect your uploaded file, you need name attribute in your input tag. So change

<input id="fileToUpload" onchange="form.submit()" type="file"/>

to

<input id="fileToUpload" name="fileToUpload" onchange="form.submit()" type="file"/>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement