Javascript 在点击上传文件之前显示图片?

Javascript 在点击上传文件之前显示图片?,javascript,html,angular,Javascript,Html,Angular,在我当前的angular项目中,我有这样的代码来上传文件: 如何更改此设置,以便在用户单击图像时可以进行上载?您可以这样做: 组件技术 import { Component, VERSION } from "@angular/core"; import { SafeUrl, DomSanitizer } from "@angular/platform-browser"; @Component({ selector: "my-app&qu

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



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

您可以这样做:

组件技术

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])
    );
  }
}
component.html

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

图像上载程序:)

实际上,您可以通过引用输入元素的id来调用click处理程序

请在此处找到解决问题的工作示例:

在HTML中:

<img src="image" alt=""  (click)="selectImage()">

点击图像?你是指用户加载的图像还是其他图像?
selectImage()
{
  let input = document.createElement('input');
  input.type = 'file';
  input.accept="image/*";
  input.click();
}