如何在文件选择上触发事件


95

我有一个表格

<form  onSubmit="return disableForm(this);" action="upload.php" method="post" name="f" id="wizecho" enctype="multipart/form-data">
    <input type="file" name="file" />
    <button onClick="return disableForm(this),ajaxUpload(this.form,'wizecho_upload.php', '&lt;br&gt;Uploading image please wait.....&lt;br&gt;'); return false;">
        Upload Image
    </button>
</form>

它是要上传图片。

在这里,我需要单击按钮以上传图像,并且必须使用onClick事件。我要删除上传按钮,并在输入中选择了文件后立即触发该事件。我怎么做??


如果您担心两次选择同一文件,那么@applecrusher会比所选答案提供更好的解决方案stackoverflow.com/a/40581284/1520304
Will Farley

Answers:


128

在文件输入上使用change事件。

$("#file").change(function(){
         //submit the form here
 });

30
当您异步提交表单时,不离开页面,然后尝试再次上传相同的文件,会发生什么?此代码将仅执行一次,第二次,选择相同的文件将不会执行更改事件
Christopher Thomas

6
@ChristopherThomas的异议正是我在这里的原因,幸运的是,几年后,下面有一个广受赞誉的回应可以解决这个问题:stackoverflow.com/a/40581284/4526479
Kyle Baker

1
当我再次选择相同文件时,更改事件不会触发。还有什么其他方法可以每次工作?
TᴀʀᴇǫMᴀʜᴍᴏᴏᴅ

1
@TᴀʀᴇǫMᴀʜᴍᴏᴏᴅ看到您上方的评论。
大卫·洛佩兹

3
答案没有使用纯JavaScript的事实是错误的
Dimitris Filippou


49

这是一个较旧的问题,需要一个新的答案,以便在接受答案的注释中解决@Christopher Thomas的担忧。如果您不离开页面然后再次选择文件,则需要在单击或执行touchstart(用于移动设备)时清除该值。即使您离开页面并使用jquery,以下内容也将起作用:

//the HTML
<input type="file" id="file" name="file" />



//the JavaScript

/*resets the value to address navigating away from the page 
and choosing to upload the same file */ 

$('#file').on('click touchstart' , function(){
    $(this).val('');
});


//Trigger now when you have selected any file 
$("#file").change(function(e) {
    //do whatever you want here
});

这个跨浏览器兼容吗?看起来它只是在使用val(''),在大多数浏览器中无法使用。
肖恩·肯德尔

您尝试使用的浏览器不兼容吗?如果您仍然遇到问题,请尝试使用其自身克隆对象。
applecrusher

2
我的问题是使用element.setAttribute("value", "")如果您不使用jQuery,则需要使用element.value = ""来使file元素真正正确清除。
菲尔(Phil)

1

在文件成功加载后执行任何操作。只需在文件处理完成后将文件控件的值设置为空字符串即可,因此即使文件名更改或不更改,.change()也将始终被调用。例如,你可以做这件事,像魅力一样为我工作

  $('#myFile').change(function () {
    LoadFile("myFile");//function to do processing of file.
    $('#myFile').val('');// set the value to empty of myfile control.
    });

1

Vue用户的解决方案,当您多次上传同一文件且@change事件未触发时,解决了问题:

 <input
      ref="fileInput"
      type="file"
      @click="onClick"
    />
  methods: {
    onClick() {
       this.$refs.fileInput.value = ''
       // further logic for file...
    }
  }

<input type =“ file” @ change =“ onFileChange” class =“ input upload-input” ref =“ inputFile” /> self。$ refs.inputFile.value =''
Pragati Dugar

0

<input type =“ file” @ change =“ onFileChange” class =“ input upload-input” ref =“ inputFile” />

onFileChange(e) {
//upload file and then delete it from input 
 self.$refs.inputFile.value = ''
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.