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.
- Replacing
onchange="form.submit()"
withonchange="alert('test');"
leads to the expected alert box after file selection. (idea from here: https://stackoverflow.com/a/1904189/11826257) - I also tried it with an extra JavaScript function as described here: https://stackoverflow.com/a/12275917/11826257. That didn’t work neither.
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"/>