选择文件后的操作

Action after file selected

我几乎是第一次在 ember(和一般的 js)工作。

场景如下:有一个 "choose file" 按钮。标准文件选择按钮已被隐藏并替换为自定义按钮。用户单击该按钮,出现文件选择 window,用户选择他们的文件,然后单击 'ok'。因为默认按钮已被隐藏,所以我需要向用户表明已选择了一个文件。我想显示一条消息表明这一点。

template.hbs 我有类似的东西

<button class="outline-only inline-block" id="my_file_button" {{action 'clickButton' 'my_file'}}>
   {{fa-icon icon="mouse-pointer"}} Choose file
</button>
<input type="file" id="my_file" name="my_file"> <!-- this is set to display: none in css file -->
{{#if my_file_button_clicked}}
  {{fa-icon icon="check-circle"}} File selected
{{/if}}

component.js 我已经定义为 actions 的一部分:

clickButton(button) {
  let self = this;
  jquery('#'+button).click();
  self.set(button+'_button_clicked', true);
}

这样做的目的是在用户单击 "choose file" 按钮后立即显示 "file selected" 消息,无论他们是完成文件选择还是单击 'cancel'。我怎样才能使消息在完成、成功选择之前不显示?

您应该将操作绑定到文件输入的 change event。在 ember.js 你是这样做的:

<input type="file" id="my_file" name="my_file" onchange={{action 'fileChanged'}}>

事件作为参数传递给操作。它包含通过 FileList 对所选文件的引用。您可以使用它来检查用户是否选择了文件。如果用户选择了一个文件,您可以将对它的引用存储在一个变量中。原始操作如下所示:

Component.extends({
  filesSelected: null, 

  actions: {
    fileChanged(event) {
      let files = event.target.files;
      this.set('filesSelected', files);
    }
  }
});

您可以使用该变量仅在已选择文件时显示图标:

{{#if filesSelected.length}}
  {{fa-icon icon="check-circle"}} File selected
{{/if}}

请注意,已经有一些 Ember 插件提供了您正在尝试实现的功能。我建议查看 Ember 观察者的文件上传类别:https://www.emberobserver.com/categories/file-upload