2016-10-08 16 views
0

ユーザーが画像をアップロードできるAngular2アプリを作成しました。私はプレビューオプションを実装したい。しかし、私はそれをimperilmentしようとすると、画像が表示されません。どのように私はこの機能を達成するのですか?Angular2 - 表示画像

UploadComponent.ts

import * as ng from '@angular/core'; 
//import { UPLOAD_DIRECTIVES } from 'ng2-uploader'; 
import {UploadService} from '../services/upload.service'; 

@ng.Component({ 
    selector: 'my-upload', 
    providers:[UploadService], 
    template: require('./upload.html') 
}) 
export class UploadComponent { 
    progress:any; 
    logo:any; 
    filesToUpload: Array<File>; 
    constructor(public us:UploadService){ 
     this.filesToUpload = []; 
    } 
    upload() { 
     this.us.makeFileRequest("http://localhost:5000/api/SampleData/Upload", this.filesToUpload) 
     .then((result) => { 
      console.log(result); 
     }, (error) => { 
      console.error(error); 
     }); 
    } 
    onFileChange(fileInput: any){ 
     this.logo = fileInput.target.files[0]; 
    } 
} 

Upload.html

<h2>Upload</h2> 
<input type="file" (change)="onFileChange($event)" placeholder="Upload image..." /> 
<button type="button" (click)="upload()">Upload</button> 
<img [src]="logo" alt="Preivew"> 

答えて

5

あなたはそれを試してみてください方法は、あなたがfileInput.target.files[0]の画像URLが、オブジェクトを得ることはありません。

画像URLを取得するには、あなたは私が他の人々のコードにFileReaderのを見保たれた理由を説明FileReaderdocumentation here

onFileChange(fileInput: any){ 
    this.logo = fileInput.target.files[0]; 

    let reader = new FileReader(); 

    reader.onload = (e: any) => { 
     this.logo = e.target.result; 
    } 

    reader.readAsDataURL(fileInput.target.files[0]); 
} 
+0

うんを使用することができます。ありがとう! – John

+0

私はそれをreader.readAsDataURL(this.logo)に変更しておくことができます。 reader.readAsDataURL(fileInput.target.files [0])の代わりに。 ?それとも、これはエラーを引き起こすでしょうか? – John