【问题标题】:How to trigger input image from img tag in Angular? [duplicate]如何从 Angular 中的 img 标签触发输入图像? [复制]
【发布时间】:2019-06-11 14:44:17
【问题描述】:

我有以下情况:

<input type="file" name="profilePicture" id="profilePicture" accept="image/*" (change)="onFileSelected($event)" style="display:none"/>
<img *ngIf="!this.profile.profilePic" src="...a static path..." />
<img *ngIf="this.profile.profilePic" [src]="this.profile.profilePic" />

并且我想根据ngIfimg 标签中显示的两个图像之一上触发输入文件。这意味着我希望在单击图像时打开上传窗口,而不像往常一样使用“文件”类型的标准输入。正如我在这里写的那样,我的代码不起作用。谁能解释一下如何从图像标签触发上传文件并隐藏输入标签?

编辑

onFileSelected只是一个处理上传图片并将对象存储在一个名为profilePicture的临时变量中的函数:

onFileSelected(event) {
  if (event.target.files.length > 0) {
     this.profilePicture = event.target.files[0];
   } else {
    this.profilePicture = undefined;
  }
}

profile 是一个包含与用户相关的所有信息的对象。

编辑二

我只使用一个 img 标签测试了代码。 以下代码也不起作用:

<input type="file" accept="image/*" (change)="onFileSelected($event)" style="display:none"/>
<img [src]="'...the static path...'"/> 

编辑 III

我的问题与this question 有关,它解决了我遇到的同样问题(不幸的是没有帮助)。

【问题讨论】:

  • 可以上传组件的代码吗
  • 我建议解释一下用户案例。我很困惑。
  • 看看我的编辑和我链接的问题。谢谢。

标签: html angular


【解决方案1】:

使用FileReader 类读取文件内容。 fileReader.result 仅在操作完成时可用。

将以下内容添加到您的 TS:

imageSource;

onFileSelected(e: Event): void {
  if (e.target.files && e.target.files[0]) {
    const imageFile = e.target.files[0];

    const fileReader = new FileReader();
    fileReader.onload = () => {
      return this.imageSource = fileReader.result;
    };

    fileReader.readAsDataURL(imageFile);
  }
}

并将imageSource 绑定到您的img 标签:

<img [src]="imageSource || 'static path'" alt="My Profile Image"/>

您只需要添加一个img 标记并适用于这两种情况,如果图像可用或从定义的路径中选择它。

【讨论】:

  • 问题是没有读取文件的内容。问题是通过单击当前显示的图像来触发上传。我正在按照您的建议仅使用一个 img 标签测试代码。
  • 不,我希望在单击图像时打开上传窗口。如果我使用 type="file" 的单独输入字段,一切正常,但我希望输入窗口允许您在单击 HTML 中的图像时选择要打开的文件。
猜你喜欢
  • 2018-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-04
  • 2018-11-02
  • 2019-12-04
  • 2019-09-08
  • 1970-01-01
相关资源
最近更新 更多