HTML 文件输入框不会触发文件选择事件并在更改事件 - angularJS 中警告

HTML File input box doesn't fire fileSelect event and caveat in onchange event - angularJS

本文关键字:文件 事件 angularJS 警告 选择 输入 HTML      更新时间:2023-09-26

我正在使用HTML文件类型控件来选择和上传文件(使用AngularJS)。我的标记如下:

<input id="uploadFile" accept=".csv" type="file" ng-file-select="model.onFileSelect($files)" onchange="angular.element(this).scope().fileNameChanged(this)">

因此,当我选择任何文件时,将触发文件名更改事件,而不是在文件选择上触发。到目前为止,这工作正常。但是,如果我选择要上传的相同文件,则不会触发 fileNameChanged 事件(因为我正在上传相同的文件),但我希望允许用户一次又一次地上传相同的文件。永远不会触发 onFileSelect 事件。

有什么方法可以解决这个问题吗?

终于让它工作了,在 HTML 中,我添加了 onclick JS 事件,如下所示:

<input id="uploadFile" onclick="myFunction();" accept=".csv" type="file" ng-file-select="model.onFileSelect($files)" onchange="angular.element(this).scope().fileNameChanged(this)">
function myFunction() {
  //setting value of null of 0th index coz in my case i allow user to upload only single file.
  //in case of multiple files, you gotta set value to null of the entire array of file list
  //returned by the control
  $('#uploadfile')[0].value = null;
  return true;
}

这样,控件将不会缓存文件名,下次选择同一文件时,将触发 onChange 事件。

如果您仍然遇到任何问题,请告诉我。

感谢萨加尔