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

时间:2018-12-02 03:41:42

标签: javascript php html

现在我有了它,因为当用户单击图像时,文件浏览器将打开。但是,我要的是打开文件浏览器并选择文件后,一旦您单击“打开”,表单将提交并且图像将上传。

这是我使用此处选择的答案得到的最接近的答案:Open File Browser on Link Click

代码:

<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>  

几乎可以正常工作。当我在文件浏览器中单击“打开”时,页面提交并刷新,但是照片根本没有上传。

但是如果我使用页面上的“提交”按钮而不是文件浏览器中的“打开”按钮进行提交,效果很好。

1 个答案:

答案 0 :(得分:0)

将事件监听器添加到文件输入中。一旦识别出更改,您就可以将其发送到他们需要去的地方。或通过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>

这应该很容易提交您的表格。