首页 > 解决方案 > 在单击以在Angular 9中上传文件之前显示图像?

问题描述

我在当前的 Angular 项目中有这样的代码来上传文件:

<input #file type="file" accept='image/*'  (change)="Loadpreview(file.files) " />

如何更改此设置,以便在用户单击图像时上传?

标签: javascripthtmlangular

解决方案


你可以这样做:

组件.ts

import { Component, VERSION } from "@angular/core";
import { SafeUrl, DomSanitizer } from "@angular/platform-browser";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  name = "Angular " + VERSION.major;
  constructor(private sanitizer: DomSanitizer) {}

  image: string | SafeUrl =
    "https://images.unsplash.com/photo-1521911528923-9c3838123490?ixlib=rb-1.2.1&auto=format&fit=crop&w=634&q=80";

  updateImage(ev) {
    this.image = this.sanitizer.bypassSecurityTrustUrl(
      window.URL.createObjectURL(ev.target.files[0])
    );
  }
}

组件.html

<p>
    Image uploader :)
</p>
<img [src]="image"  (click)="selectImage.click()">
<input type="file" (change)="updateImage($event)" style="display: none" #selectImage>

您实际上是通过引用输入元素的 id 来调用点击处理程序

请在此处找到您的问题的工作示例:https ://stackblitz.com/edit/stackoverflow-62501330


推荐阅读