typescript 在Angular中上传文件之前预览多个图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48939699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:14:58  来源:igfitidea点击:

Preview multiple image before upload file in Angular

htmlangulartypescript

提问by Paco Zevallos

How can I preview multiple images that I have selected before uploading them in Angular?

在 Angular 中上传之前,如何预览我选择的多个图像?

enter image description here

在此处输入图片说明

I have managed to do it but only with one image, even though I select several, only one recognizes me. I think the use of *ngForis a good alternative but I'm not sure how to raise it. Any ideas?

我设法做到了,但只有一张图片,即使我选择了几张,也只有一张能认出我。我认为使用*ngFor是一个不错的选择,但我不确定如何提出它。有任何想法吗?

myComponent.html

我的组件.html

<img *ngIf="url" [src]="url" class="rounded mb-3" width="180">
<input type="file" multiple (change)="detectFiles($event)">

myComponent.ts

myComponent.ts

detectFiles(event) {
this.selectedFiles = event.target.files;
if (event.target.files && event.target.files[0]) {
  var reader = new FileReader();
  reader.onload = (event: any) => {
    this.url = event.target.result;
  }
  reader.readAsDataURL(event.target.files[0]);
}
}

回答by ConnorsFan

As shown in this stackblitz, you can store the image URLs in an array and display them with ngFor:

如此 stackblitz所示,您可以将图像 URL 存储在一个数组中并使用以下命令显示它们ngFor

<div>
    <img *ngFor="let url of urls" [src]="url" class="rounded mb-3" width="180">
</div>
<input type="file" multiple (change)="detectFiles($event)">

The array of URLs is filled in detectFiles:

填充了 URL 数组detectFiles

export class AppComponent {

  urls = new Array<string>();

  detectFiles(event) {
    this.urls = [];
    let files = event.target.files;
    if (files) {
      for (let file of files) {
        let reader = new FileReader();
        reader.onload = (e: any) => {
          this.urls.push(e.target.result);
        }
        reader.readAsDataURL(file);
      }
    }
  }
}

回答by Cacoon

we can use *ngFor like so:

我们可以像这样使用 *ngFor :

<div *ngFor="let img of arrayOfImg; let i = index">
      <img [src]="img" class="rounded mb-3" width="180">
</div>

I added the index because its useful to have sometimes, if the array isnt just simply a string array, instead a json or object array you might have to do this:

我添加了索引,因为它有时很有用,如果数组不仅仅是一个字符串数组,而是一个 json 或对象数组,您可能必须这样做:

[src]="img.url"

[src]="img.url"

I am not sure how to upload/select the files for upload but I would assume when you select them from the computer and/or URL that you simply add their URL to an array

我不确定如何上传/选择要上传的文件,但我假设当您从计算机和/或 URL 中选择它们时,您只需将它们的 URL 添加到数组中