如何从Angular 4中的多个选定图像文件中获取第一个图像URL

时间:2018-11-25 13:11:03

标签: html angular typescript

我对Angle 4不熟悉,需要在上传之前显示所选图像文件的第一张图像。

我已经搜索并找到关于stackoverflow的解决方案,但是我无法获得第一个图像url。它显示了所有选中的图像。

参考:Preview multiple image before upload file in Angular

app.component.ts

export class AppComponent {

    urls = new Array<string>();
    selectedImageToShow : string ;

      detectFiles(event) {

        selectedImageToShow = // how to get the first image url 

        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);
          }
        }
      }
    } 

app.component.html

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

谁能帮我解决这个问题。

2 个答案:

答案 0 :(得分:0)

app.component.html应该看起来像这样:

git filter-branch -f --index-filter 'git rm --cached --ignore-unmatch path-to-large-file' --prune-empty --tag-name-filter cat -- --all

答案 1 :(得分:0)

您可以使用文件索引来获取第一个文件名。

您的files是一个数组,您可以使用以下索引循环或抓取:

let first_file = event.target.files[0]; // without loop. Use name property for file name

let file_name = "";

// Using loop
for(let i = 0; i < files.length; i++ ) {
  file_name = files[i]; // use index 0 to store first file.
}