【问题标题】:Im still able to select any file after declaring to only accept image files in an input在声明只接受输入中的图像文件后,我仍然能够选择任何文件
【发布时间】:2020-02-26 18:39:52
【问题描述】:

这是我的表格:

<form #optionsForm="ngForm" novalidate (ngSubmit)="saveOptions()" id="optionsForm">
  <div class="modal-body">
    <div class="form-group">
      <label for="customFile">Icon</label>
      <div class="custom-file">
        <input type="file" accept="image/*" class="custom-file-input" id="customFile" 
               name="customerFile" (change)="handleFileInput($event.target.files)" required>
        <label class="custom-file-label" for="customFile" 
               id="customerFileLabel">Select Icon</label>
      </div>
    </div>
    <div *ngIf="logo.imageInBase64" class="row">
      <label id="previewLabel">Preview:</label>
      <div class="report-logo">
        <img alt="{{logo.name}}" src="{{logo.imageInBase64}}" class="logo-image">
      </div>
    </div>
    <button type="submit" class="btn btn-secondary" aria-hidden="true" 
            [disabled]="!optionsForm.valid">
      <i class="fa fa-floppy-o"></i> Save
    </button>
  </div>
</form>

这就是没有和选择文件时的样子:

我目前有两个问题。首先,我尝试用accept="image/* 定义只有图像应该被输入接受。但它唯一做的就是用图像过滤器打开文件管理器,但我仍然能够切换到所有文件并选择一个非图像文件。有没有办法避免这种情况?

第二个问题是表单验证。如果表单使用[disabled]="!optionsForm.valid" 无效,我将禁用按钮。我将所需的属性放入输入,因此如果未选择任何输入,则应该使表单无效并禁用按钮,但它目前没有这样做。即使我没有选择任何文件,表格仍然有效。

【问题讨论】:

  • 您无法控制用户在上传对话框中切换到“所有文件”。

标签: html angular forms


【解决方案1】:

您还可以使用图像指定扩展名,如下所示。这将只允许指定的扩展名用于文件选择和上传。我希望这对你有用。

<form #optionsForm="ngForm" novalidate (ngSubmit)="saveOptions()" id="optionsForm">
  <div class="modal-body">
    <div class="form-group">
      <label for="customFile">Icon</label>
      <div class="custom-file">
        <input type="file" accept="image/x-png,image/gif,image/jpeg" class="custom-file-input" id="customFile" 
               name="customerFile" (change)="handleFileInput($event.target.files)" required>
        <label class="custom-file-label" for="customFile" 
               id="customerFileLabel">Select Icon</label>
      </div>
    </div>
    <div *ngIf="logo.imageInBase64" class="row">
      <label id="previewLabel">Preview:</label>
      <div class="report-logo">
        <img alt="{{logo.name}}" src="{{logo.imageInBase64}}" class="logo-image">
      </div>
    </div>
    <button type="submit" class="btn btn-secondary" aria-hidden="true" 
            [disabled]="!optionsForm.valid">
      <i class="fa fa-floppy-o"></i> Save
    </button>
  </div>
</form>

【讨论】:

    猜你喜欢
    • 2018-03-08
    • 2021-08-23
    • 2014-08-16
    • 2012-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-17
    相关资源
    最近更新 更多