【发布时间】:2017-08-23 12:58:57
【问题描述】:
我正在尝试构建一个允许用户选择本地图像的页面。然后应该显示它。我是网络世界的新手,所以我搜索了很多,基本上复制了一些其他 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);
}
}
选择文件后的结果
(右边的调试输出,所有方法调用,只是图片还是空的,显示的是替代文字。)
那么……我做错了什么?
【问题讨论】:
-
仅作记录,所选图片不是白色背景上的“源”字...
标签: html image angular typescript filereader