在文件浏览器中单击“打开”时如何提交照片上传

问题描述:

Right now I have it as when a user clicks on the image the file browser will open up. But what I want is for after the file browser has opened and a file is chosen, once you click "open" the form will submit and the image will upload.

This is the closest I have gotten using the answer chosen here: Open File Browser on Link Click

code:

<div class="col-sm-6">
    <img height="120" width="140" id="profileImage" alt="profile-image" class="userimg" style="margin-bottom: 1rem;" onclick="document.getElementById('imageFile').click();" src="<?php echo $image_src; ?>" />
</div>

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>?id=<?php echo $childId; ?>" method="post" enctype="multipart/form-data" id="imageForm" name="imageForm" class="text-center">
  <!--  <input type="submit" id="btn-imageUpload" value="Submit" name="submit" /> -->
    <input type="file"  style="display:none;" id="imageFile" name="profile-photo" onchange="this.form.submit() enctype=”multipart/form-data” capture/>
</form>  

It almost worked.. When I click "open" in the file browser the page submits and refreshes, but the photo was not uploaded at all.

But it works fine if I submit using the "submit" button on the page instead of the "open" button in the file browser.

Add an event listener to your file input. Once it recognizes a change you can send them to where they need to go. Or make the request via AJAX.

var form = document.querySelector('#profile_image'),
      input = document.querySelector('input[name="picture"]');

input.addEventListener('change', e => {
  e.preventDefault();
  // form.submit(); // Uncomment this line or change it to your preferred AJAX mechanism
  document.querySelector('body').innerHTML += 'Event Listener worked!';
});
  
<form action="/upload/profile/<?=$childId?>" method="POST" id="profile_image">

  <input type="file" name="picture" />

</form>

This should easily submit your form.

</div>