在浏览器中显示本地图像文件

时间:2017-08-23 12:58:58

标签: html5 image angular typescript filereader

我正在尝试构建一个允许用户选择本地图像的页面。然后应该显示它。我是网络世界的新手,所以我搜索了很多内容,基本上复制了一些其他的StackOverflow帖子。它应该工作。但事实并非如此。我可以看到正在加载的文件,它的图像数据被写入元素,但元素不会改变。它只是保持白色,显示其替代文字。

app.component.html:

<div style="text-align:center">
  <h1>Sprite Sheet Converter</h1>
</div>

<div class="container">
  <form>
    <div class="row">
      <label class="control-label" for="sourceFileControl">Source:</label>
      <input class="form-control" type="file" class="form-control" id="sourceFileControl" name="sourceFileControl" (change)="load($event)" />
    </div>

    <div class="row">
      <img #sourceImage src="" alt="Source" width="100" height="100"/>
    </div>

  </form>

  <img #destinationImage alt="Destination"/>
</div>

app.component.ts:

import {Component, ViewChild} from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  @ViewChild('sourceImage') sourceImage: HTMLImageElement;
  @ViewChild('destinationImage') destinationImage: HTMLImageElement;

  load(event: EventTarget): void {
    const eventObj: MSInputMethodContext = <MSInputMethodContext> event;
    const target: HTMLInputElement = <HTMLInputElement> eventObj.target;
    const files: FileList = target.files;
    const file = files[0];
    console.log(file);

    const reader  = new FileReader();
    const img = this.sourceImage;

    reader.onloadend = function() {
      img.src = reader.result;
      console.log('done loading');
      console.log(img);
    };

    console.log('now loading');
    reader.readAsDataURL(file);
  }
}

选择文件后的结果

(调试输出到右边,调用所有方法,只是图片仍然是空的,并显示它的替换文字。)

enter image description here

那么......我做错了什么?

2 个答案:

答案 0 :(得分:1)

当您使用function关键字时,您将失去对this的访问权限。您需要使用arrow function () =>代替。此外,在特定情况下,您不需要ViewChild。为了工作,我会将您的代码更改为以下内容:

使用*ngIf确保图像在有数据之前不会加载。将图像源绑定到包含源图像数据的某个变量。目标图像也是如此。将<img>标记更改为以下内容:

<img *ngIf="sourceImage" src={{sourceImage}} alt="Source" width="100" height="100"/>

<img *ngIf="destinationImage" src={{destinationImage}} alt="Destination"/>

...并且您的component.ts代码将如下所示:

import {Component} from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  sourceImage: string;
  destinationImage: string;

  load(event: EventTarget): void {
    const eventObj: MSInputMethodContext = <MSInputMethodContext> event;
    const target: HTMLInputElement = <HTMLInputElement> eventObj.target;
    const files: FileList = target.files;
    const file = files[0];
    console.log(file);    
    const reader  = new FileReader();    
    reader.onloadend = () => {
      console.log('done loading');
      this.sourceImage = reader.result;

    };

    console.log('now loading');
    reader.readAsDataURL(file);
  }
}

答案 1 :(得分:-2)

检查您是否在DOM中获得 SRC 属性。如果在那里检查正确的图像源是否存在。尝试为img元素提供宽度和高度样式

相关问题