Angular2 - 显示图像

时间:2016-10-08 14:05:20

标签: image angular typescript

我创建了一个允许用户上传图片的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"> 

3 个答案:

答案 0 :(得分:6)

您尝试的方式是,您不会使用fileInput.target.files[0]获取图片网址,而是获取对象。

要获取图片网址,您可以使用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]);
}

答案 1 :(得分:1)

  
  filesToUpload: Array<File> = [];
  url: any;
  image: any;
  
//file change event 
  
  filechange(fileInput: any) {

    this.filesToUpload = <Array<File>>fileInput.target.files;
    this.image = fileInput.target.files[0]['name'];
    this.readurl_file(event);
  }
  
//read url of the file
  
  readurl_file(event) {
    if (event.target.files && event.target.files[0]) {
      const reader = new FileReader();
      reader.onload = (eve: any) => {
        this.url = eve.target.result;
      };
      reader.readAsDataURL(event.target.files[0]);
    }
  }
  
   
   <div  class="form-group">
      <label for="image">Image</label>
      <input type="file"  class="form-control"  (change)="filechange($event)" placeholder="Upload file..." >
    </div>
    <div class="container">
        <img [src]="url">
    </div>
  
  

答案 2 :(得分:0)

使用FileReader并不是一个好习惯。如果图片太大,则会因为onload函数将整个图片加载到RAM中而使浏览器崩溃。

更好的方法是使用:

url = URL.createObjectURL($event.target.files[0]);

然后,用DomSanitizer展示出来:

this.sanitizer.bypassSecurityTrustUrl(url)

所以在ts:

constructor(private sanitizer: DomSanitizer) {} 

onFileChange(fileInput: any){
    this.url = URL.createObjectURL($event.target.files[0]);
}

get previewUrl(): SafeUrl {
   return this.sanitizer.bypassSecurityTrustUrl(this.url);
}

在html中:

<img [src]="previewUrl"/>