Javascript HTML <input type='file'> 文件选择事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3528359/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:02:11  来源:igfitidea点击:

HTML <input type='file'> File Selection Event

javascripthtmljavascript-events

提问by Moon

Let's say we have this code:

假设我们有这个代码:

<form action='' method='POST' enctype='multipart/form-data'>
    <input type='file' name='userFile'><br>
    <input type='submit' name='upload_btn' value='upload'>
</form>

which results in this:

这导致:

image showing browse and upload button

显示浏览和上传按钮的图像

When the user clicks the 'Browse...' button, a file search dialog box is opened:

当用户单击“浏览...”按钮时,将打开一个文件搜索对话框:

image showing a file search dialog box with a file selected

显示选择了文件的文件搜索对话框的图像

The user will select the file either by double-clicking the file or by clicking the 'Open' button .

用户将通过双击文件或单击“打开”按钮来选择文件。

Is there a Javascript Event that I can use to be notified after after the file is selected?

在选择文件后,是否有一个 Javascript 事件可以用来通知我?

回答by Anurag

Listen to the change event.

监听更改事件。

input.onchange = function(e) { 
  ..
};

回答by Clem

When you have to reload the file, you can erase the value of input. Next time you add a file, 'on change' event will trigger.

当您必须重新加载文件时,您可以删除输入的值。下次添加文件时,将触发 'on change' 事件。

document.getElementById('my_input').value = null;
// ^ that just erase the file path but do the trick

回答by Zanon

jQuery way:

jQuery方式:

$('input[name=myInputName]').change(function(ev) {

    // your code
});

回答by anthony

The Change event gets called even if you click on cancel..

即使您单击取消,也会调用 Change 事件。

回答by RegarBoy

That's the way I did it with pure JS:

这就是我用纯 JS 做的方式:

var files = document.getElementById('filePoster');
var submit = document.getElementById('submitFiles');
var warning = document.getElementById('warning');
files.addEventListener("change", function () {
  if (files.files.length > 10) {
    submit.disabled = true;
    warning.classList += "warn"
    return;
  }
  submit.disabled = false;
});
#warning {
    text-align: center;
}

#warning.warn {
 color: red;
 transform: scale(1.5);
 transition: 1s all;
}
<section id="shortcode-5" class="shortcode-5 pb-50">
    <p id="warning">Please do not upload more than 10 images at once.</p>
    <form class="imagePoster" enctype="multipart/form-data" action="/gallery/imagePoster" method="post">
        <div class="input-group">
       <input id="filePoster" type="file" class="form-control" name="photo" required="required" multiple="multiple" />
     <button id="submitFiles" class="btn btn-primary" type="submit" name="button">Submit</button>
        </div>
    </form>
</section>