预览图像选择器
在此示例中,我们将创建一个图像选择器,在上传之前预览你的图片。预览器还支持将文件拖放到输入中。在这个例子中,我只是要介绍上传单个文件,但你可以修改一下以使多文件上传工作。
图像 preview.html
这是我们图像预览的 html 布局
<!-- Icon as placeholder when no file picked -->
<i class="material-icons">cloud_upload</i>
<!-- file input, accepts images only. Detect when file has been picked/changed with Angular's native (change) event listener -->
<input type="file" accept="image/*" (change)="updateSource($event)">
<!-- img placeholder when a file has been picked. shows only when 'source' is not empty -->
<img *ngIf="source" [src]="source" src="">
图像 preview.ts
这是我们的 <image-preview>
组件的主要文件
import {
Component,
Output,
EventEmitter,
} from '@angular/core';
@Component({
selector: 'image-preview',
styleUrls: [ './image-preview.css' ],
templateUrl: './image-preview.html'
})
export class MtImagePreviewComponent {
// Emit an event when a file has been picked. Here we return the file itself
@Output() onChange: EventEmitter<File> = new EventEmitter<File>();
constructor() {}
// If the input has changed(file picked) we project the file into the img previewer
updateSource($event: Event) {
// We access he file with $event.target['files'][0]
this.projectImage($event.target['files'][0]);
}
// Uses FileReader to read the file from the input
source:string = '';
projectImage(file: File) {
let reader = new FileReader;
// TODO: Define type of 'e'
reader.onload = (e: any) => {
// Simply set e.target.result as our <img> src in the layout
this.source = e.target.result;
this.onChange.emit(file);
};
// This will process our file and get it's attributes/data
reader.readAsDataURL(file);
}
}
another.component.html
<form (ngSubmit)="submitPhoto()">
<image-preview (onChange)="getFile($event)"></image-preview>
<button type="submit">Upload</button>
</form>
就是这样。比 AngularJS 1.x 更容易。我实际上是根据我在 AngularJS 1.5.5 中制作的旧版本制作了这个组件。