我在当前的 Angular 项目中有这样的代码来上传文件:
<input #file type="file" accept='image/*' (change)="Loadpreview(file.files) " />
如何更改此设置,以便在用户单击图像时上传?
最佳答案
你可以这样做:
组件.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
关于javascript - 在单击以在Angular 9中上传文件之前显示图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62501330/