首页 > 解决方案 > 选择文件后的操作

问题描述

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

这是场景:有一个“选择文件”按钮。标准文件选择按钮已被隐藏并替换为自定义按钮。用户单击该按钮,出现文件选择窗口,用户选择他们的文件,然后单击“确定”。因为默认按钮已被隐藏,所以我需要向用户表明已选择了一个文件。我想显示一条消息来表明这一点。

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);
}

这样做的目的是在用户单击“选择文件”按钮时立即显示“文件选择”消息,无论他们是完成文件选择还是单击“取消”。我怎样才能使它在完成、成功的选择之前不会显示消息?

标签: ember.jshandlebars.js

解决方案


您应该将操作绑定到文件输入的change事件。在 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 Observer 上的文件上传类别:https ://www.emberobserver.com/categories/file-upload


推荐阅读