简体   繁体   English

如何捕捉“选定文件”事件?

[英]How can I catch the “file selected” event?

I have the following dialog box in my application : 我的应用程序中有以下对话框:

对话框

When the user presses the Add logo button, following things should happen: 当用户按下“ Add logo按钮时,将发生以下情况:

  1. A file selectio dialog should pop up. 将会弹出一个文件选择对话框。
  2. After the user has selected the file, a function should be called (which will update the image). 用户选择文件后,应调用一个函数(它将更新图像)。

I have the following code for this. 我有以下代码。 The markup for file selection looks like this: 文件选择的标记如下所示:

<button class="btn" ng-click="$ctrl.addLogo()">Add logo</button>

$ctrl.addLogo() is defined as ( source ) $ctrl.addLogo()定义为( source

$ctrl.addLogo = function() {
    console.log("'Add logo' button clicked");
    var uploadForm = document.createElement('form');
        var fileInput = uploadForm.appendChild(document.createElement('input'));
    fileInput.type = 'file';
        fileInput.name = 'images';
    fileInput.multiple = true;
        fileInput.click(function() {
        console.log("Click callback called");
    });
};

When I press the Add logo button, the file selection dialog does open, but the Click callback called message does not appear in the console. 当我按下“ Add logo按钮时,文件选择对话框确实打开,但是“ Click callback called消息未出现在控制台中。 This means that I cannot detect, when the user has selected a file (or closed the dialog box with "Cancel"). 这意味着当用户选择文件时(或者用“取消”关闭对话框),我无法检测到。

How can I implement a reaction to the user selecting a file (or cancelling the dialog)? 如何对用户选择文件(或取消对话框)做出反应?

When the user selects a file in an input with type="file" , it is the change event that is fired. 当用户在input选择type="file" ,将触发change事件。

If you replace your click listener by a change listener, it should work :) 如果您将click侦听器替换为change侦听器,则它应该可以工作:)

fileInput.click(function() {
    console.log("Click callback called");
});

must become: 必须成为:

fileInput.change(function() {
    console.log("Click callback called");
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM